String and &str
String
is Rust's String
type, where strings are saved in heap.
&str
is a string slice, pointed to the real strings.
String literals are &str
, they are saved at the "static storage" area in a program, so technically they are type of 'static &str
.
As parameter
If a function takes &str
as parameter, you can pass String
, &str
and String literals to it. For example:
fn test(&str) {
}
let s1 = String::from("hello");
// to pass String to this function, we need change it to string slice
test(&s1[..]);
// directly pass a string slice
let s2 = &s1[1..3];
test(s2);
// b/c string literals are &str, we can directly pass string literals
let s3 = "Hello World";
test(s3);
Conversion
To change String to &str, we can use &str[..]
like the above example.
To change string literals to String, we can use the to_string()
function, for example "hello".to_string()
or String::from("hello")
;
Example
You can infer if a string function returning String or &str by checking if the function changes the origin string letters.
For example, .trim()
will remove the leading and trailing spaces, which means it can return a pointer to the original string starting with the first non-space letter and ending with the last ending space letter, it doesn't need to change the original string or create a new string.
While .replace()
or the to_lowercase()
method will need to create a new string to make the change, because just create a pointer pointing to the original string won't work.
fn string_slice(arg: &str) {
println!("{}", arg);
}
fn string(arg: String) {
println!("{}", arg);
}
fn main() {
string_slice("blue"); // string literals are &str
string("red".to_string()); // to_string return String
string(String::from("hi")); // String::from return String
string("rust is fun!".to_owned()); // to_owned return String
string("nice weather".into()); // Same as String::from
string(format!("Interpolation {}", "Station")); // Created a new String
string_slice(&String::from("abc")[0..1]); // Create a slice
string_slice(" hello there ".trim()); // create a slice
string("Happy Monday!".to_string().replace("Mon", "Tues")); // Create a new String
string("mY sHiFt KeY iS sTiCkY".to_lowercase()); // Create a new String
}
Top comments (0)