其他分享
首页 > 其他分享> > Rust 结构体

Rust 结构体

作者:互联网

fn main(){
    ///  实例化结构体
    let  width = 1024;
    let height = 576;
    let image = GrayscaleMap{
        pixels: vec![0;width * height],
        size:(width, height)
    };
    println!("{:?}",image.size);
    let  hokey = Boom{
        name: "Hokey".to_string(),
        height:60,
        health:100,
        position:(100.0, 200.0, 0.0),
        intent: BroomIntent::FetchWater
    };

    let (hokey1,hokey2) = hokey.chop();
    println!("{:#?}\n{:#?}",hokey1,hokey2);
    

}
#[derive(Debug)]
struct Boom{
    name: String,
    height:u32,
    health:u32,
    position: (f32, f32, f32),
    intent: BroomIntent
}
#[derive(Debug,Copy,Clone)]
enum BroomIntent{ FetchWater,  DumpWater }

impl Boom{
    /// # 构造函数
    fn new(name:String,height:u32,health:u32,position:(f32,f32,f32),intent:BroomIntent) -> Boom{
        Boom{name,height,health,position,intent}
    }
    ///  # 一分为二
    /// 
    fn chop(self) ->(Boom,Boom){
        //高度为原始的一半,其余的不变
        // 使用 .. 来继承另一个相同类型的结构体实例的其余字段
        let mut broom1 = Boom{height: self.height/2, ..self};
        // 因为字段 name  是不可复制的String 类型,所以需要显示的 clone
        let mut broom2 = Boom{name: broom1.name.clone(), ..broom1};
        // 给每一个Boom起个不一样的名字
        broom1.name.push_str("_1");
        broom2.name.push_str("_2");
        (broom1, broom2)
    }
    
}

///  #  命名字段结构体
/// 结构体默认是私有的,
/// 要想让这个结构体对外部可见,需要在它的定义之前加上pub,前且其字段也要相应的增加pub 
#[derive(Debug,Clone)]
struct GrayscaleMap{
    pixels: Vec<u8>,
    size: (usize,usize)
}

impl GrayscaleMap{
    /// * 当局部变量或者参与与字段同名时,可以采用如下的简写方式
    /// 
    fn new_map(size:(usize, usize),pixels: Vec<u8>) -> GrayscaleMap{
        assert_eq!(pixels.len(),size.0 *size.1);
        GrayscaleMap{pixels,size}
    }
}

标签:name,height,f32,let,Boom,broom1,Rust,结构
来源: https://blog.csdn.net/weixin_41767230/article/details/118060705