当前位置:网站首页>Rust string slicing, structs, and enumeration classes
Rust string slicing, structs, and enumeration classes
2022-07-03 00:37:00 【Wang Ziqing Big Ben】
1. String slice (slice): Is a partial reference to the data value
fn main() {
let s = String::from("broadcast");
let part1 = &s[0..5];
let part2 = &s[5..9];
println!("{}={}+{}", s, part1, part2);
}

The above figure explains the principle of string slicing .
among ,“…” This symbol needs to be understood ,x…y Express [x,y) The meaning of .…y Express 0~y.x… Express x To end ,… It means from beginning to end .
There are two string types that we can distinguish here :str and string type .
All string constants contained in double quotation marks have the overall type property of str:let s=“loot”;String The type is Rust A data type provided by the standard public library , Its function is more perfect —— It supports string appending 、 Emptying and other practical operations .String and str In addition to having a character start position attribute and a string length attribute, there is also a capacity (capacity) attribute .
String and str All support slicing , The result of slicing is &str Data of type .
There is a quick way to string Type conversion to str type
let s1 = String::from("hello");
let s2 = &s1[..];
2. Non string slicing
Except that strings can be sliced , Other linear data structures also support slicing , For example, an array of .
fn main() {
let arr = [1, 3, 5, 7, 9];
let part = &arr[0..3];
for i in part.iter() {
println!("{}", i);
}
}
3.Rust Definition and examples of structure
Definition :
struct Site {
domain: String,
name: String,
nation: String,
found: u32
}
example :
let runoob = Site {
domain: String::from("www.runoob.com"),
name: String::from("RUNOOB"),
nation: String::from("China"),
found: 2013
// You can also change some of them , use ..runoob
};
4. Tuple structure
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);
}
This color and coordinate format is still very important , Access by subscript .
5. Output structure
Debugging , It is very useful to show an example of a structure completely . But if we write a format manually, it will be very inconvenient . therefore Rust It provides a convenient way to output a whole structure :
#[derive(Debug)] // Import debug library
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30, height: 50 };
println!("rect1 is {:?}", rect1);
// If there are too many attributes , have access to {:#?} Place holder .
}
6. Structure method
Method (Method) And the function (Function) similar , It's just used to manipulate structure instances .
If you have learned some object-oriented languages , Then you must know that functions are generally placed in class definitions and used in functions this Represents the instance being operated .
Rust The language is not object-oriented , This can be seen from the innovation of its ownership mechanism . But the precious idea of object-oriented can be found in Rust Realization .
The first argument to the struct method must be &self, No need to declare type , because self Not a style, but a keyword .
Calculate the area of a rectangle :
struct Rectangle {
width: u32,
height: u32,
} // Definition
impl Rectangle {
// Method
fn area(&self) -> u32 {
self.width * self.height // Function expression
}
}
fn main() {
let rect1 = Rectangle {
width: 30, height: 50 }; // example
println!("rect1's area is {}", rect1.area());
}
7.Rust Enumeration class
In some practical application problems , Some variables are limited in a limited range . For example, there are only seven days a week , There is only... In a year 12 Months, etc , Such variables can be defined as enumeration types . The definition of enumeration type lists all possible values , Note: the value of the variable of this enumeration type cannot exceed the defined range .
enum Book {
Papery(u32),
Electronic(String),
}
let book = Book::Papery(1001);
let ebook = Book::Electronic(String::from("url://..."));
8.match grammar
This and switch Branches are very similar to ,switch It is easy to forget to add break And the series connection operation problem .
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);
}
}
}
// It only matches one , No output after .
fn main() {
let t = "abc";
match t {
"abc" => println!("Yes"),
_ => {
},
}
}
9.Option Enumeration class
Option yes Rust Enumeration classes in the standard library , This class is used to fill in Rust I won't support it null Reference blank .
边栏推荐
- Free we media essential tools sharing
- Basic 10 of C language: array and pointer
- FAQ | FAQ for building applications for large screen devices
- 微信小程序获取某个元素的信息(高、宽等),并将px转换为rpx。
- University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
- Where can I check the foreign literature of economics?
- Linux Software: how to install redis service
- 详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
- Andorid 获取系统标题栏高度
- 字符设备注册常用的两种方法和步骤
猜你喜欢

Multiprocess programming (II): Pipeline

CMake基本使用

setInterval定时器在ie不生效原因之一:回调的是箭头函数

How SQLSEVER removes data with duplicate IDS

Automated defect analysis in electronic microscopic images

Linux Software: how to install redis service

为什么网站打开速度慢?

Shell 实现文件基本操作(sed-编辑、awk-匹配)

Rust字符串切片、结构体和枚举类

Maya fishing house modeling
随机推荐
如何系统学习机器学习
关于XML一些介绍和注意事项
Nc50528 sliding window
Monitor container runtime tool Falco
【JetCache】JetCache的配置说明和注解属性说明
helm 基础学习
Graduation summary
机器学习:numpy版本线性回归预测波士顿房价
One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
Understanding and application of least square method
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
Free we media essential tools sharing
Where can I find the English literature of the thesis (except HowNet)?
Andorid 获取系统标题栏高度
【单片机项目实训】八路抢答器
[Luogu p4320] road meets (round square tree)
Multiprocess programming (V): semaphores
百数不断创新,打造自由的低代码办公工具
Pat 1030 travel plan (30 points) (unfinished)
Centos7 one click compilation to build MySQL script