No, then s2
will be an &String
. You can see this in the following way:
fn main() {
let s1 = String::from("sdasdasd");
let s2 = &s1;
let () = s2;
}
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | let () = s2;
| ^^ -- this expression has type `&std::string::String`
| |
| expected struct `std::string::String`, found `()`
That said, Rust has a feature that automatically converts an &String
into an &str
when such a conversion is required by the surrounding types.
fn main() {
let s1 = String::from("sdasdasd");
// explicitly set the type to &str, triggering the conversion
let s2: &str = &s1;
let () = s2;
}
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | let () = s2;
| ^^ -- this expression has type `&str`
| |
| expected `str`, found `()`
This feature is known as Deref
coercion, which you can read about in the Rust book. It is not specific to strings, e.g. it also works for &Vec<u8> → &[u8]
.
Note that the same conversion can be performed explicitly with as_str
:
fn main() {
let s1 = String::from("sdasdasd");
// explicitly convert to &str
let s2 = s1.as_str();
}