Rust入门之struct

什么是struct?

struct:结构体,可以理解为JAVA中的对象

定义struct

使用struct关键字

struct Cuboid {//长方体
    length: f64,//长
    width: f64,//宽
    height: f64,//高
}

//初始化,每一个字段都要复制,不然编译不过
fn main() {
    let cuboid = Cuboid {
        width: 30.7,
        length: 40.9,
        height: 10.5
    };
    println!("获取长字段的值:{}",cuboid.length);
}

输出:
获取长字段的值:40.9

可以对实例用mut关键字修饰,mut修饰的struct实例其所有字段都是可变的

fn main() {
    let mut cuboid = Cuboid {
        length: 40.9,
        width: 30.7,
        height: 10.5
    };
    cuboid.length = 10.1;
    println!("获取长字段的值:{}",cuboid.length);
}
输出:
获取长字段的值:10.1

struct也可以作为函数返回值

fn main() {
    let cuboid1 = return_struct();
}

fn return_struct()->Cuboid{
    Cuboid {
        length: 40.9,
        width: 30.7,
        height: 10.5
    }
}

输出:
返回struct:Cuboid {
    length: 40.9,
    width: 30.7,
    height: 10.5,
}
struct更新语法

基于一个struct实例,想创建另一个实例时,我们可以使用struct更新语法

fn main() {
    let cuboid = Cuboid {
        length: 40.9,
        width: 30.7,
        height: 10.5,
    };

    let cuboid2 = Cuboid {
        length: cuboid.length,//部分字段相同时
        width: 30.7,
        height: 10.5,
    };

    let cuboid2 = Cuboid {
        ..cuboid//全部字段相同时,直接用..表示
    };
}
Tuple struct
fn main() {
    let color = Color(0, 0, 0);
    let point = Point(108.9, 89.1);
}
struct Color (u32,u32,u32);
struct Point(f64, f64);
Unit Like struct

没有字段的struct

struct Cuboid {
   
}
struct方法与函数

方法和函数类似:fn、方法名、参数、返回值

不同之处:

1、方法定义在struct内

2、第一个参数为self

3、对struct使用impl关键字,定义impl方法块


接下来尝试一个例子
fn main() {
    let mut cuboid = Cuboid {
        length: 40.9,
        width: 30.7,
        height: 10.5,
    };
    let volume = cuboid.volume();
    println!("长方体体积:{}", volume);
    println!("长方体实体:{:#?}", cuboid);

    let cube = Cuboid::cube(30f64);

    let cube_volume = cube.volume();
    println!("正方体体积:{}", cube_volume);
    println!("正方体实体:{:#?}", cube);//对宏输出内容格式化
}


#[derive(Debug)]//用Debug调试模式
struct Cuboid {
    length: f64,
    width: f64,
    height: f64,
}

impl Cuboid {
     //关联函数通常用于构造器
    fn cube(size: f64) -> Cuboid {
        Cuboid {
            width: size,
            length: size,
            height: size,
        }
    }

    //计算体积函数
    fn volume(&self) -> f64 {
        self.width * self.length * self.height
    }
}

输出:
长方体体积:13184.114999999998
长方体实体:Cuboid {
    length: 40.9,
    width: 30.7,
    height: 10.5,
}
正方体体积:27000
正方体实体:Cuboid {
    length: 30.0,
    width: 30.0,
    height: 30.0,
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值