Which should i choose between this style for writing rust code?

    //OPTION 1
    let y: &mut String = &mut x; 

    //OPTION 2
    let y: = &mut x;

I'm currently learning rust via The Book. That is very fun. Of course, I still have other chapters that could cover this question. But I prefer to ask here :grinning:.

So, I'm using Vs codium. Is Rust automatically detect that let y = & mut x; have data type &mut String or this task is done by Rust Analyzer/Vs codium format standard. Is it better to write explicitly or not?

Thank you, best regards.

It depends[1].

Do you care? As in, is knowing the type of y useful in the specific piece of code you're writing? If it is useful, do you need it there? Can the type be easily inferred from surrounding context? If it's obvious what the type of x is, you maybe don't need to spell out the type of y.

Do you feel the code is easy to misunderstand if someone doesn't know what the type of y is? It might be worth makeing it explicit to aid comprehension. Maybe the type of y is particularly important for the surrounding code.

Like I said, it depends.

You should use whichever option makes the code easier to read and understand, without burying the reader in unnecessary detail. There is no objectively correct answer.

The compiler does not need Rust Analyzer or any code formatter to do its job. Those exist to help you, not the compiler. Type inference is something the compiler has to be able to do, otherwise let y = &mut x wouldn't be valid syntax.

  1. (The standard answer to almost any difficult question.) ↩ī¸Ž

1 Like

Thanks for your answer. After read your comment i prefer mentioning it explicitly so it's easier to understand in re-reading my code.

Sometimes code is easier to understand when you leave out redundant information. For example, if a function is only handling f32 numerical types it makes it harder to read if every temporary variable has an explicit type.

You will also encounter places where you want the compiler to infer parts of the type. A typical example is the target of a collect

let names: Vec<_> = some_iterable.iter().filter_map(...).collect();
1 Like

There's value in matching the style of the majority of other code available in that language, which is why tools like formatters and linters exist.

I would say explicitly typing is on the unusual side in Rust code in general: it normally implies that there's something different and important happening with the type, such as contextually providing a type to the right, or that the type itself is important, such as a MutexGuard, and you want to call it out.

In general though, so long as what you write passes rustfmt and clippy (cargo fmt and cargo clippy respectively) you're not really doing anything "wrong" stylistically.

1 Like