I'm trying to understand the concept of strings and string slices.
fn say_hello_slice(slice: &str) {
println!("Hey {}", slice);
}
fn say_hello_string(string: &String) {
println!("{:?}", string);
}
fn print_int(int_ref: &i32) {
println!("{:?}", int_ref);
}
fn main() {
let slice: &str = "you";
let s: String = String::from("String");
say_hello_slice(slice);
say_hello_slice(&s);
let number: i32 = 12345;
print_int(&number);
say_hello_string(&s);
}
This program gives the below output when I compile and run:
Hey you
Hey String
12345
"String"
I understand that when &
is added to the binding it becomes a reference to its binding type. For example, &
to number
in above program becomes &i32
.
I don't understand how it works when I add &
to String
and it becomes &str
.
A string slice is a reference to part of a String , and it looks like this: let s = String::from("hello world"); let hello = &s[0.. 5]; let world = &s[6.. 11]; Rather than a reference to the entire String , hello is a reference to a portion of the String , specified in the extra [0..
In Rust, we can use the trim() method of a string to remove the whitespace characters around that string. This method removes the leading and trailing whitespace characters of a given string.
String is the dynamic heap string type, like Vec : use it when you need to own or modify your string data. str is an immutable1 sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer.
A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime.
You have just witnessed the Deref
trait. This trait has three uses:
*
operator)In your case, because String
implements Deref<Target = str>
this means that &s
is coerced into a &str
.
More info here.
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