How do I tell Rust that I want a struct which contains a slice of a string?
I've tried:
struct Welcome {
version: &str,
}
but the compiler complains:
src/chat.rs:16:14: 16:18 error: missing lifetime specifier [E0106]
src/chat.rs:16 version: &str,
From my limited understanding of Rust, I think a string slice is a pointer+length into some text allocated elsewhere.
I want the lifetime of the string slice to be the life time of the allocated text.
Rust owned String type, the string itself lives on the heap and therefore is mutable and can alter its size and contents.
To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().
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..
Your understanding is mostly correct and you were just one step away from what you want. You can use a named lifetime in this way:
struct Welcome<'a> {
version: &'a str,
}
This says that the &str reference must have the same lifetime as the containing Welcome struct. More info on lifetimes can be found in the lifetimes guide
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