当前位置:网站首页>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 引用的空白。
边栏推荐
- Markdown使用教程
- What is the standard format of a 2000-3000 word essay for college students' classroom homework?
- Mutual exclusion and synchronization of threads
- Pytorch 20 realizes corrosion expansion based on pytorch
- Automated defect analysis in electron microscopic images-论文阅读笔记
- Blue decides red - burst CS teamserver password
- Shell脚本基本使用
- Custom throttling function six steps to deal with complex requirements
- Install docker and use docker to install MySQL
- NC50965 Largest Rectangle in a Histogram
猜你喜欢

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

Monitor container runtime tool Falco

maya渔屋建模

Markdown使用教程
![洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举](/img/a3/55bb71d39801ceeee421a0c8ded333.png)
洛谷_P2010 [NOIP2016 普及组] 回文日期_折半枚举

TypeError: Cannot read properties of undefined (reading ***)

Cmake basic use

One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
![[MCU project training] eight way answering machine](/img/a3/6a50619cd16269bf485a4a273677aa.jpg)
[MCU project training] eight way answering machine

Feature Engineering: summary of common feature transformation methods
随机推荐
[golang syntax] map common errors golang panic: assignment to entry in nil map
collections. What is the purpose of chainmap- What is the purpose of collections. ChainMap?
Bypass AV with golang
【雅思阅读】王希伟阅读P2(阅读填空)
[target detection] r-cnn, fast r-cnn, fast r-cnn learning
Multiprocess programming (V): semaphores
Andorid gets the system title bar height
Slf4j + logback logging framework
【单片机项目实训】八路抢答器
秒杀系统设计
Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
NC17059 队列Q
NC24840 [USACO 2009 Mar S]Look Up
Introduction and use of ftrace tool
pod生命周期详解
zhvoice
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
What website can you find English literature on?
Go自定义排序