Structs that borrow in Rust
A struct holding a reference carries a lifetime, tying it to the data it reads.
struct Header<'a> {
name: &'a str,
value: &'a str,
}
impl<'a> Header<'a> {
fn parse(line: &'a str) -> Option<Header<'a>> {
let (name, value) = line.split_once(": ")?;
Some(Header { name, value })
}
}
fn main() {
let raw = String::from("Content-Type: text/html");
if let Some(header) = Header::parse(&raw) {
println!("{} = {}", header.name, header.value);
}
println!("{:?}", Header::parse("nonsense").is_none());
}
How it works
- The lifetime is declared on the struct and used on the field.
- The struct cannot outlive the text it points into.
- This is how zero-copy parsers avoid allocating.
Keywords and builtins used here
HeaderOptionSomeStringfnifimplletmainparsestrstruct
The run, in numbers
- Lines
- 19
- Characters to type
- 415
- Tokens
- 150
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 86 seconds.
Step 2 of 4 in Lifetime annotations, step 2 of 11 in Lifetimes & interior mutability.