Rust 专题
您的位置:rust > Rust专题 > Rust结构体更新语法
Rust结构体更新语法
作者:--    发布时间:2019-11-20

使用struct更新语法从其他实例创建新实例。
当新实例使用旧实例的大部分值时,可以使用struct update语法。考虑两名员工employee1employee2

  • 首先,创建employee结构体的实例employee1
let employee1 = employee{  
    employee_name : string::from("maxsu"),  
    employee_id: 12,  
    employee_profile : string::from("it工程师"),  
    active : true,  
};
  • 其次,创建employee2的实例。 employee2实例的某些值与employee1相同。 有两种方法可以声明employee2实例。
    第一种方法是在没有语法更新的情况下声明employee2实例。
let employee2 = employee{  
    employee_name : string::from("maxsu"),  
    employee_id: 11,  
    employee_profile : employee1.employee_profile,  
    active : employee1.active,  
};

第二种方法是使用语法更新声明employee2实例。

let employee2 = employee{  
    employee_name : string::from("h3"),  
    employee_id: 11,  
    ..employee1  
};

语法..指定其余字段未显式设置,并且它们与给定实例中的字段具有相同的值。

下面来看一个结构的简单示例:

struct triangle  
{  
    base:f64,  
    height:f64,  
}  

fn main()  
{  
    let triangle= triangle{base:20.0,height:30.0};  
    print!("area of a right angled triangle is {}", area(&triangle));  
}  

fn area(t:&triangle)->f64  
{  
    0.5 * t.base * t.height  
}

执行上面示例代码,得到以下结果 -

area of a right angled triangle is 300

在上面的例子中,创建了三角形(triangle)的结构体,它包含两个变量,即直角三角形的底边和高度。三角形(triangle)的实例是在main()方法中创建的。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册