Referenzen
Rust enforces a number of rules for references that make them always safe to use. One rule is that references can never be null, making them safe to use without null checks. The other rule weāll look at for now is that references canāt outlive the data they point to.
fn main() { let x_ref = { let x = 10; &x }; println!("x: {x_ref}"); }
This slide should take about 3 minutes.
-
This slide gets students thinking about references as not simply being pointers, since Rust has different rules for references than other languages.
-
Weāll look at the rest of Rustās borrowing rules on day 3 when we talk about Rustās ownership system.
More to Explore
- Rustās equivalent of nullability is the
Optiontype, which can be used to make any type ānullableā (not just references/pointers). We havenāt yet introduced enums or pattern matching, though, so try not to go into too much detail about this here.