I just read the Rust documentation about string data types, which states:
Rust has more than only
&str
s though. AString
is a heap-allocated string. This string is growable, and is also guaranteed to be UTF-8.
Trouble: I want to explicitly declare variable type like follows:
let mystring : &str = "Hello"; // this works
let mystring : String = "Hello"; // this does not. Why?
It's because the second mystring
is not a String
, but a &'static str
, i.e. a statically allocated string literal.
In order to create a String
in this manner (from a literal), you need to write let mystring = String::from("Hello")
(Rust docs).
Because a &str
is not a String
.
There are a few ways you can make that string literal a String
instance though:
let mystring = String::from("Hello");
// ..or..
let mystring: String = "Hello".into();
// ..or..
let mystring: String = "Hello".to_string();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With