#Defining string best practice

1 messages · Page 1 of 1 (latest)

dreamy jewel
#

See attached image. note the ": &str" is optional and my code will compile and run with and without it. Why does it recommend me to do this and is it always a good idea to include? My background is from Java so I'm learning this new syntax
ferrisOwO

#

I should note this is on vscode using the rust analyzer plugin

unkempt aspen
#

I think you might be misinterpreting that

#

It's not really a recommendation, it's just so you know what type it is

dreamy jewel
#

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 spongehmm

quasi garden
dreamy jewel
#

I get ya. So is there any reason to include this type in the code? or just let the compiler deal with it?

quasi garden
#

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

stray patrol
#

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

dreamy jewel
#

thanks for the help guys

rare ridge
# dreamy jewel I get ya. So is there any reason to include this type in the code? or just let t...

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.