当前位置:网站首页>Rust development - Struct usage example
Rust development - Struct usage example
2022-08-08 05:27:00 【The knower goes against】
结构体
1.定义
pub struct User
{
user_id : u32,
user_name: String,
is_vip : bool,
}
2.实例化
Here initialization must all assign values to all members,不像C++,A value can be initialized individually
let user : User = User {
user_id: 100, user_name: "matt".to_string(), is_vip: false};
simplify assignment,The field names in the structure can be omitted when the fields in the structure are the same as the declared assignment fields,The literal values that follow are different,So the field name must be specified
let user_id : u32 = 101;
let user_name = "matting".to_string();
let vip = true;
let user2:User = User {
user_id, user_name, is_vip:vip};
3.获取值
let user_name = user.user_name;
4.可变访问,A struct must be declared mutable for variable access,All elements in a struct are mutable.
let mut user : User = User {
user_id: 100, user_name: "matt".to_string(), is_vip: false};
user.user_name = "matt45m".to_string();
5.更新语法,When creating a new instance based on an instance,Update syntax can be used.…userThe values representing the next two fields come from the first structure
let mut user : User = User {
user_id: 100, user_name: "matt".to_string(), is_vip: false};
let user_id : u32 = 101;
let user2:User = User {
user_id, ..user};
6.Tuple struct
Tuple struct The whole has a given name,But the elements inside have no names.
struct Color(u8,u8,u8);
let black = Color(0,0,0);
7.struct的方法(rust的struct类似于c++的类)
- 方法是在struct(enum、trait对象)的上下文中定义的.
- 方法的第一个参数是self,selfpoints to the called onestruct 实例(类似于C++的this指针).
- 方法在 impl (implement)块中定义的
impl StructName {} - The first parameter of the method can be used &self,It can also be acquired for ownership or variable borrowing,like other parameters.
- new方法可以构造struct,可以理解为构造函数
pub struct SlotNode
{
user_name :String,
start_node : u32,//开始节点
end_node : u32,//结束节点
}
impl SlotNode
{
pub fn new() -> Self
{
SlotNode {
user_name: String::new(), start_node: 0, end_node: 1024}
}
pub fn get_end_node(&self) -> u32
{
self.end_node
}
}
instantiation and access
let slot_node = SlotNode::new();
println!("{}\n", slot_node.get_end_node());
8.struct继承
rust structInheritance does not existC++That powerful feature,And there is a big difference in concept,In fact, it is not inherited in the traditional sense.
// Define a struct similar to the parent class
#[derive(Debug)]
struct Animal
{
gender: String,
}
impl Animal
{
fn new(gender: String) -> Self
{
Self {
gender }
}
}
impl Animal
{
pub fn print_gender(&self)
{
println!("Animal {}", self.gender);
}
fn set_gender(&mut self, gender: String)
{
self.gender = gender;
}
}
// 定义子类
#[derive(Debug)]
struct Cat
{
animal: Animal,
name: String,
}
impl Cat
{
fn new(animal: Animal, name: &str) -> Self
{
Self {
animal , name: name.to_string()}
}
}
impl Cat
{
fn as_animal(&self) -> &Animal
{
&self.animal
}
fn as_mut_animal(&mut self) -> &mut Animal
{
&mut self.animal
}
}
fn main() {
let student = Animal::new("male".to_string());
let mut tome = Cat ::new(student, "小橘");
tome.animal.print_gender();
tome.animal.set_gender("femininity".to_string());
tome.animal.print_gender();
println!("{:#?}", tome);
let a: &Animal = tome.as_animal();
a.print_gender();
let a: &mut Animal = tome.as_mut_animal();
a.set_gender("femininity".to_string());
a.print_gender();
}

边栏推荐
猜你喜欢

千亿级、大规模:腾讯超大 Apache Pulsar 集群性能调优实践

TCP/IP基本实现

Matlab simulation of photovoltaic mppt maximum power control based on disturbance observation method

TSF微服务治理实战系列(二)——服务路由

研发医疗器械产品需要做的测试

Servlet---ServletConfig类使用介绍

Spark entry learning-3-SparkSQL data abstraction

【leetcode】剑指 Offer(专项突击版)汇总

Session and cookie usage

C语言-函数
随机推荐
Hundreds of billions, large-scale: performance tuning practice of Tencent's super-large Apache Pulsar cluster
【Win10】若干睡眠问题及对策
单主机docker 搭建 redis-cluster
分布式事务 :可靠消息最终一致性方案
Unity鼠标光标使用学习
Go-Excelize API source code reading (10) - SetActiveSheet(index int)
Sqlmap + dnslog injection of repetition
The big and small end problem caused by union union
报错:[Intervention] Unable to preventDefault inside passive event listener due to target ...
2022-08-07 mysql/stonedb slow SQL-subquery-semi-join
Unity-CharacterController(角色控制器)
使用ffmpeg解码音频sdl(push)播放
【u-boot】u-boot的驱动模型分析
毕设——基于人脸表情的桌面交互精灵设计(分享一下成果,附上人脸表情的数据集和自己训练出来yolov5模型以及基于PYQT5运行yolov5的交互界面)
【js基础】闭包的几种情况(代码)
奇怪的魔法(组合数)
类似Bugfree的9大在线缺陷管理软件
多维度数组拉平到一维
如何批量导入文件,并全部自定义重命名为相同文件名
Leetcode78. 子集