其他分享
首页 > 其他分享> > 【Rust】生存期-结构体

【Rust】生存期-结构体

作者:互联网

环境

概念

参考:https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime/struct.html

示例

main.rs

#[derive(Debug)]
struct Borrowed<'a>(&'a i32);

#[derive(Debug)]
struct NamedBorrowed<'a> {
    x: &'a i32,
    y: &'a i32,
}

#[derive(Debug)]
enum Either<'a> {
    Num(i32),
    Ref(&'a i32),
}

fn main() {
    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);
}

总结

了解了 Rust 中的结构体的生存期参数的标注。

附录

标签:borrowed,derive,struct,i32,生存期,let,println,Rust,结构
来源: https://www.cnblogs.com/jiangbo44/p/15703799.html