Type Inferrence not Recognized

Sometimes _ refers to an inferred type and sometimes it doesn’t. You can’t meaningfully search for '_' or 'underscore' in the reference to find out the rules. Anyway, such rules are a burden and learning obstacle. If there’s a concept, like “_ refers to the inferred type,” it should hold everywhere!

Types can often be rather lengthy, especially generic ones. In constructor type functions (which don’t return Self, e.g. typestate transitions,) as the last thing, one typically repeats the type verbosely. As a legacy of C++, which chose an operator as a bracket, don’t forget to turbofish it, no plain copy & paste! To avoid all that I wanted to infer it, but the compiler didn’t even understand. (The first variant might be unlikely to be used much, it’s just for completeness.)

fn f_unit() -> SomeLongnamedUnitType {
	// SomeLongnamedUnitType
    _
}

fn f_struct(x: f32) -> SomeComplicatedStruct<Type> {
	// SomeComplicatedStruct::<Type> { x }
    _ { x }
}

fn f_tuple(x: f32) -> SomeComplicatedTuple<Type> {
	//  SomeComplicatedTuple::<Type>(x)
    _(x)
}

This should be logically unambiguous, and syntactically as well. The only other thing (???) that can currently have an underscore at the beginning of a statement is

_ = must_use_value();

So I suggest in all contexts where the expected type is clear, to generalise _ to be that type. Looking forward to a Rust that feels even more consistent.

RFC 3444

2 Likes

That's not type position: https://rust-lang.github.io/rfcs/1506-adt-kinds.html#tuple-structs.

Ah, ok, “like a function” and “the constructor function is not exactly a fn item, there are subtle differences (e.g. with regards to privacy checks), but it’s a close approximation.”

Anyway, named tuples are a bit of a mess. Nice for quick hacks, but at 3 members, the addressing starts to get hairy. Named fields usually win big time for maintainability. So leaving them out of this is fine with me.

Rust analyzer should have a function to help turn them into a normal struct!

Oh, that's not a thing yet?

2 Likes

I didn’t stumble on any. At least no refactor of a tuple struct is offered.

On my r-a i have "convert to named struct" as a code action. When I select a tuple struct

I just upgraded to latest RA in VS code.

I find no such thing. What is a code action? There is the command palette, where I can search a ton of things. This includes super useful RA stuff, like showing a macro expansion. But neither your conversion, nor "code action".

default keybinding for showing code actions / quick fixes is ctrl + . (at least on windows)