January 2019
Beginner to intermediate
554 pages
13h 31m
English
When we create impl blocks for structs with references, we need to repeat the lifetime declarations and definitions again. For instance, if we made an implementation for the struct Foo we defined previously, the syntax would look like this:
// lifetime_impls.rs#[derive(Debug)]struct Number<'a> { num: &'a u8 }impl<'a> Number<'a> { fn get_num(&self) -> &'a u8 { self.num } fn set_num(&mut self, new_number: &'a u8) { self.num = new_number }}fn main() { let a = 10; let mut num = Number { num: &a }; num.set_num(&23); println!("{:?}", num.get_num());}
In most of these cases, this is inferred from the types themselves and then, we can omit the signatures with <'_> syntax.
Read now
Unlock full access