Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable of type `String` does not work [duplicate]

I just read the Rust documentation about string data types, which states:

Rust has more than only &strs though. A String 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?
like image 674
Fusion Avatar asked Dec 08 '22 21:12

Fusion


2 Answers

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).

like image 36
ljedrz Avatar answered May 03 '23 14:05

ljedrz


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();
like image 173
Simon Whitehead Avatar answered May 03 '23 14:05

Simon Whitehead