当前位置:网站首页>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 .
边栏推荐
- University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
- 【单片机项目实训】八路抢答器
- 多进程编程(五):信号量
- University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
- node_modules删不掉
- [IELTS reading] Wang Xiwei reading P1 (reading judgment question)
- How do educators find foreign language references?
- Helm basic learning
- 关于XML一些介绍和注意事项
- Multiprocess programming (V): semaphores
猜你喜欢
[shutter] Introduction to the official example of shutter Gallery (learning example | email application | retail application | wealth management application | travel application | news application | a
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
setInterval定时器在ie不生效原因之一:回调的是箭头函数
Shell implements basic file operations (cutting, sorting, and de duplication)
Sysdig analysis container system call
布隆过滤器
百数不断创新,打造自由的低代码办公工具
CMake基本使用
ftrace工具的介绍及使用
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
随机推荐
Centos7 one click compilation to build MySQL script
node_ Modules cannot be deleted
logback配置文件
The most painful programming problem in 2021, adventure of code 2021 Day24
Nc50528 sliding window
Nc17059 queue Q
[Luogu p4320] road meets (round square tree)
Markdown使用教程
Why is the website slow to open?
Is there a specific format for English papers?
机器学习:numpy版本线性回归预测波士顿房价
Linux Software: how to install redis service
多进程编程(三):消息队列
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
Kubernetes simple introduction to writing YML
University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
Go custom sort
Set up nacos2 X cluster steps and problems encountered
NC17059 队列Q
布隆过滤器