Named tuple fields (no type system changes)

Just allow adding names to tuple fields for documentation purposes. e.g. fn into_raw_parts(self) -> (ptr: NonNull<T>, len: usize, cap: usize).

Like function pointers, these do not change the type of the tuple. (a: u32, b: u32) is still the same as (u32, u32). Fields cannot be accessed by field name.

In the future, fields could be accessed by name with some sort of "name inference", but that is more complicated and potentially fragile.

1 Like

As written this isn't very different from the currently accepted syntax of just

fn into_raw_parts(self) -> (/*ptr*/ NonNull<T>, /* len */ usize, /* cap */ usize)

I'm assuming though you'd want a warning for calling this function

let (ptr, cap, len) = foo.into_raw_parts(); // whoops

But in anything even slightly more complex you'd probably want names like in a struct. And yes I'd love it if you could inline declare returning a struct, nonymous (Vec::into_raw_parts::Return) or otherwise.

Just tacking on nice ways to write documentation is probably an easy no. As part of a larger proposal for inline return types and parameters would be excellent. In summary, love the idea but we should write it ... -> {ptr: NonNull<T>, len: usize, cap: usize}.

7 Likes

What's the problem that's making you not make a struct for this?

I'd rather fix that problem instead, TBH.

(I've been pondering things like #t-lang > Spitballing: structs with opposite defaults? @ :speech_balloon: for example.)

3 Likes

I suppose this would be for cases where you often immediately destructure the return value. In that case structs are much more annoying to destruct because you have to name their type. That could however be solved by allowing to use _ for the struct name and letting the type be inferred from the return type.

8 Likes

This has been talked about many, many times in the general form.

I wonder if maybe we could do it just in patterns as a first step? Any downsides that exist for structs in expressions basically don't exist in patterns, at least at first instinct.

Something like

let _ { a, b, c } = whatever;

seems clearly fine, since sure it doesn't show the type, but neither does

let a = whatever.a;
let b = whatever.b;
let c = whatever.c;
18 Likes

There didn't seem to be any technical objections to doing this in patterns when I raised a substantially identical proposal five years ago. Maybe someone should draft up an RFC (not volunteering)?

10 Likes