mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-15 18:12:43 +00:00
42 lines
902 B
Rust
42 lines
902 B
Rust
// ./src/scope/lifetime/struct.md
|
|
|
|
|
|
// A type `Borrowed` which houses a reference to an
|
|
// `i32`. The reference to `i32` must outlive `Borrowed`.
|
|
#[derive(Debug)]
|
|
struct Borrowed<'a>(&'a i32);
|
|
|
|
// Similarly, both references here must outlive this structure.
|
|
#[derive(Debug)]
|
|
struct NamedBorrowed<'a> {
|
|
x: &'a i32,
|
|
y: &'a i32,
|
|
}
|
|
|
|
// An enum which is either an `i32` or a reference to one.
|
|
#[derive(Debug)]
|
|
enum Either<'a> {
|
|
Num(i32),
|
|
Ref(&'a i32),
|
|
}
|
|
|
|
fn part0() {
|
|
let x = 18;
|
|
let y = 15;
|
|
|
|
let single = Borrowed(&x);
|
|
let double = NamedBorrowed { x: &x, y: &y };
|
|
let reference = Either::Ref(&x);
|
|
let number = Either::Num(y);
|
|
|
|
println!("x is borrowed in {:?}", single);
|
|
println!("x and y are borrowed in {:?}", double);
|
|
println!("x is borrowed in {:?}", reference);
|
|
println!("y is *not* borrowed in {:?}", number);
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|