当前位置:网站首页>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();
}

边栏推荐
- 数据库系统原理与应用教程(080)—— MySQL 练习题:操作题 186-193(二十四):综合练习
- 线索二叉树
- reduce具体使用以及使用reduce,toString,flat进行数组降维
- 28. Anomaly detection
- 28.异常检测
- 使用 Zap 和 W3af 进行 Web 应用程序漏洞评估
- 顺序表(下)
- Eighteen, OIDC OAuth2 】 【 the understanding of the application
- The difference between classification, object detection, semantic segmentation, and instance segmentation
- The only OpenCyphal/UAVCAN tutorial in the whole network (11) Write a Cyphal protocol parsing tool with candump and gawk tools
猜你喜欢
随机推荐
Lecture 84 Biweekly t4 6144 and Lecture 305 t4 6138
【着色器实现Tricolor三原色型变效果_Shader效果第十八篇】
postgresql中连接两张表更新第三张表(updata)
Week 8 Generative Adversarial Networks(生成对抗网络 GAN)
C语言力扣第58题之最后一个单词的长度。从后往前遍历
nonebot插件:说话的艺术
Leetcode78. Subset
Checkerboard Coloring Problem
[Redis] Redis Learning - Transaction
Database sub-database sub-table, when?How to divide?
Week 9 10 Neural Networks
gcc/g++使用
Connect two tables to update the third table (updata) in postgresql
温故知新—Activity的五种启动模式
10 must-have free tools for self-media people to operate quickly and efficiently
Codeforces Round #684 (Div. 1)
使用ffmpeg解码音频sdl(push)播放
线索二叉树
Week 9 10 Neural Networks
基础了解虚拟 DOM









