Rust:结构体与方法与关联函数

获取以像素为单位的长方形的宽度和高度,并计算出长方形的面积

使用结构体

struct Rectangle{
    width:u32,
    height:u32,
}

fn main() {
    let rect = Rectangle{
        width:10,
        height:10,
    };

    let area:u32 = rectangele_area(&rect);//传引用,否则这个正方形就会失去它的属性的所有权,属性是不能借的,是自己固有的
    println!("{}", area);
}

fn rectangele_area(rect:&Rectangle)->u32{
    return rect.width * rect.height;
}
  • 方法与函数类似,它们使用fn关键字和名称声明,可以拥有参数和返回值,同时包含在某处调用该方法时会执行的代码。不过方法与函数是不同的,因为它们在结构体的上下文中被定义,并且它们的第一个参数总是self,它代表调用该方法的结构体实例
  • 调用方法:使用.运算符调用实例的方法

方法允许为结构体实例指定行为

//
struct Rectangle{
    width:u32,
    height:u32,
}

impl Rectangle{
     //这个结构体拥有求面积的方法
    fn area(&self)->u32{   //不可变地借用 self:我们并不想获取所有权,只希望能够读取结构体中的数据,而不是修改写入结构体数据。
         return self.width * self.height;
    }

    //行为:长方形能否包含另一个长方形
    fn can_hold(&self, other:&Rectangle)->bool{
        return self.height > other.height && self.width > other.width;
    }

    fn change_width(&mut self, width:u32){
        self.width = width;
    }
}

fn main() {
    let rect1 = Rectangle{
        width:10,
        height:10,
    };

    let mut rect2 = Rectangle{
        width:5,
        height:5,
    };

    println!("the rectangle's area is {}", rect1.area());
    println!("rect1 can hold rect2 ? {}", rect1.can_hold(&rect2)); //可变变量允许以不允许修改的权限借出自己的值

    rect2.change_width(15);
    println!("{}", rect2.width)
}
  • impl的另一个有用的功能是:允许在impl中定义不以self作为参数的函数,这被称为关联函数,因为它们与结构体相关联。但是它们仍然是函数而不是方法,
    因为它们并不作用于一个结构体的实例。
  • 使用方法:使用::运算符。::语法用于关联函数和模块创建的命名空间
//
struct Rectangle{
    width:u32,
    height:u32,
}

impl Rectangle{
     //这个结构体拥有求面积的方法
    fn area(&self)->u32{   //不可变地借用 self:我们并不想获取所有权,只希望能够读取结构体中的数据,而不是修改写入结构体数据。
         return self.width * self.height;
    }

    //行为:长方形能否包含另一个长方形
    fn can_hold(&self, other:&Rectangle)->bool{
        return self.height > other.height && self.width > other.width;
    }

    fn change_width(&mut self, width:u32){
        self.width = width;
    }
}

//关联函数
impl Rectangle{
    //关联函数常常被用作返回一个结构体新实例的函数,比如构建一个正方形的关联函数:
    fn square(size:u32)->Rectangle{
        return Rectangle{width:size, height:size}
    }
}
fn main() {
    let square1 = Rectangle::square(15);
    let area = square1.area();
    println!("area is {}", area);
}

参考:https://kaisery.github.io/trpl-zh-cn/ch05-03-method-syntax.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值