#Defining string best practice
1 messages · Page 1 of 1 (latest)
I think you might be misinterpreting that
It's not really a recommendation, it's just so you know what type it is
Ah, it's just vccode says "double click to insert" when I hover over it and then if I double click it adds it explicitly to the statement
so I was wondering if generally do people usually leave it implicit or explicitly define the string
dynamic types make me 
In general in rust you don't need to specify the type if the compiler can infer it. Rust is also statically typed so there are no dynamic types here.
When you define a string literal like "bar" it's type will always be &str.
I get ya. So is there any reason to include this type in the code? or just let the compiler deal with it?
I would say there's no real reason for strings like this.
99% of the time the compiler will be able to figure it out - I usually specify the type in situations where it cant
e.g. if you're using .collect() on an iterator, it needs to know the type which you're trying to collect into and this would require either type on the variable or a turbofish
it can also be useful to add type annotations that aren't necessary so that, if at some point you make a mistake, the compiler will give you a type error mentioning that expected type, instead of a type error somewhere else
or just for documentation
thanks for the help guys
It depends how much you care and how complicated the context is to figure it out.
For a variable like this initialized from a string literal, I'd probably never annotate it explicitly because "of course" a string literal is a &str.
But for the other end of the spectrum, see https://github.com/scottmcm/rust/commit/ascii-char-in-fmt#diff-5c3682e8974cc4b780f07f1a1fd2fed4332e66d7645dc72fa7c29dbdd785ccdaR306, where I added a type annotation because it's an over-100-lines function where it's extremely hard to figure out the type as a human, and in an intermediate version of the code I was getting some particularly confusing error messages because I'd accidentally added conflicting constraints.
