当前位置:网站首页>Rust字符串切片、结构体和枚举类
Rust字符串切片、结构体和枚举类
2022-07-02 23:31:00 【王紫情大本蛋】
1.字符串切片(slice):就是对数据值的部分引用
fn main() {
let s = String::from("broadcast");
let part1 = &s[0..5];
let part2 = &s[5..9];
println!("{}={}+{}", s, part1, part2);
}
上图解释了字符串切片的原理。
其中,“…”这个符号需要了解一下,x…y表示[x,y)的含义。…y表示0~y。x…表示x到结束,…表示开始到结尾。
有两个字符串类型我们在这里区分一下:str和string类型。
凡是用双引号包括的字符串常量整体的类型性质都是 str:let s=“loot”;String 类型是 Rust 标准公共库提供的一种数据类型,它的功能更完善——它支持字符串的追加、清空等实用的操作。String 和 str 除了同样拥有一个字符开始位置属性和一个字符串长度属性以外还有一个容量(capacity)属性。
String 和 str 都支持切片,切片的结果是 &str 类型的数据。
有一个快速的方法将string类型转换成str类型
let s1 = String::from("hello");
let s2 = &s1[..];
2.非字符串切片
除了字符串可以切片外,其他还有一些线性数据结构也支持切片操作,例如数组。
fn main() {
let arr = [1, 3, 5, 7, 9];
let part = &arr[0..3];
for i in part.iter() {
println!("{}", i);
}
}
3.Rust结构体的定义和实例
定义:
struct Site {
domain: String,
name: String,
nation: String,
found: u32
}
实例:
let runoob = Site {
domain: String::from("www.runoob.com"),
name: String::from("RUNOOB"),
nation: String::from("China"),
found: 2013
//也可以变化其中一部分,用..runoob
};
4.元组结构体
fn main() {
struct Color(u8, u8, u8);
struct Point(f64, f64);
let black = Color(0, 0, 0);
let origin = Point(0.0, 0.0);
println!("black = ({}, {}, {})", black.0, black.1, black.2);
println!("origin = ({}, {})", origin.0, origin.1);
}
这种颜色和坐标的格式还是很重要的,通过下标进行访问。
5.输出结构体
调试中,完整地显示出一个结构体实例是非常有用的。但如果我们手动的书写一个格式会非常的不方便。所以 Rust 提供了一个方便地输出一整个结构体的方法:
#[derive(Debug)] //导入调试库
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30, height: 50 };
println!("rect1 is {:?}", rect1);
//如果属性太多的话,可以使用{:#?}占位符。
}
6.结构体方法
方法(Method)和函数(Function)类似,只不过它是用来操作结构体实例的。
如果你学习过一些面向对象的语言,那你一定很清楚函数一般放在类定义里并在函数中用 this 表示所操作的实例。
Rust 语言不是面向对象的,从它所有权机制的创新可以看出这一点。但是面向对象的珍贵思想可以在 Rust 实现。
结构体方法的第一个参数必须是 &self,不需声明类型,因为 self 不是一种风格而是关键字。
计算一个矩形的面积:
struct Rectangle {
width: u32,
height: u32,
} //定义
impl Rectangle {
//方法
fn area(&self) -> u32 {
self.width * self.height //函数表达式
}
}
fn main() {
let rect1 = Rectangle {
width: 30, height: 50 }; //实例
println!("rect1's area is {}", rect1.area());
}
7.Rust枚举类
在一些实际应用问题中,有些变量的取值被限定在一个有限的范围内。例如一周只有七天,一年只有12个月等,可以把此类变量定义为枚举类型。枚举类型的定义中列举出所有可能的取值,说明为该枚举类型的变量取值不能超过定义的范围。
enum Book {
Papery(u32),
Electronic(String),
}
let book = Book::Papery(1001);
let ebook = Book::Electronic(String::from("url://..."));
8.match语法
这个和switch分支很像,switch容易存在忘记添加break而产生的串接运行问题。
fn main() {
enum Book {
Papery {
index: u32},
Electronic {
url: String},
}
let book = Book::Papery{
index: 1001};
let ebook = Book::Electronic{
url: String::from("url...")};
match book {
Book::Papery {
index } => {
println!("Papery book {}", index);
},
Book::Electronic {
url } => {
println!("E-book {}", url);
}
}
}
//只会匹配一个,后面不输出。
fn main() {
let t = "abc";
match t {
"abc" => println!("Yes"),
_ => {
},
}
}
9.Option枚举类
Option 是 Rust 标准库中的枚举类,这个类用于填补 Rust 不支持 null 引用的空白。
边栏推荐
- Multiprocess programming (V): semaphores
- 多进程编程(二):管道
- NC50528 滑动窗口
- Program analysis and Optimization - 9 appendix XLA buffer assignment
- Pytorch 20 realizes corrosion expansion based on pytorch
- Basic use of shell script
- TypeError: Cannot read properties of undefined (reading ***)
- Which software can translate an English paper in its entirety?
- v8
- MySQL 23道经典面试吊打面试官
猜你喜欢
Gan model architecture in mm
[MCU project training] eight way answering machine
秒杀系统设计
教育学大佬是怎么找外文参考文献的?
Explain in detail the significance of the contour topology matrix obtained by using the contour detection function findcontours() of OpenCV, and how to draw the contour topology map with the contour t
UART、RS232、RS485、I2C和SPI的介绍
What are the recommended thesis translation software?
Architecture: database architecture design
【单片机项目实训】八路抢答器
字符设备注册常用的两种方法和步骤
随机推荐
Where can I find the English literature of the thesis (except HowNet)?
form表单实例化
哪些软件可以整篇翻译英文论文?
AcWing_188. 武士风度的牛_bfs
zhvoice
Confluence的PDF导出中文文档异常显示问题解决
[golang syntax] map common errors golang panic: assignment to entry in nil map
Architecture: database architecture design
[shutter] open the third-party shutter project
布隆过滤器
洛谷_P1149 [NOIP2008 提高组] 火柴棒等式_枚举打表
多进程编程(一):基本概念
Shell脚本基本使用
【雅思阅读】王希伟阅读P1(阅读判断题)
[IELTS reading] Wang Xiwei reading P2 (reading fill in the blank)
Gan model architecture in mm
maya渔屋建模
多进程编程(四):共享内存
FAQ | FAQ for building applications for large screen devices
Pat 1030 travel plan (30 points) (unfinished)