当前位置:网站首页>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 .
边栏推荐
- 【雅思阅读】王希伟阅读P1(阅读判断题)
- The "2022 China Digital Office Market Research Report" can be downloaded to explain the 176.8 billion yuan market in detail
- Nacos+openfeign error reporting solution
- Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
- 布隆过滤器
- Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
- NC24840 [USACO 2009 Mar S]Look Up
- Automated defect analysis in electronic microscopic images
- 详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
- Multiprocess programming (V): semaphores
猜你喜欢
pageoffice-之bug修改之旅
Monitor container runtime tool Falco
Markdown使用教程
Sysdig analysis container system call
Gan model architecture in mm
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
【雅思阅读】王希伟阅读P1(阅读判断题)
What are the recommended thesis translation software?
FAQ | FAQ for building applications for large screen devices
Introduction and use of ftrace tool
随机推荐
多进程编程(一):基本概念
LeedCode1480. Dynamic sum of one-dimensional array
Hundreds of continuous innovation to create free low code office tools
pageoffice-之bug修改之旅
node_modules删不掉
Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
NC24840 [USACO 2009 Mar S]Look Up
pod生命周期详解
可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场
Slf4j + logback logging framework
Introduction of UART, RS232, RS485, I2C and SPI
Is there a specific format for English papers?
CMake基本使用
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
Program analysis and Optimization - 9 appendix XLA buffer assignment
Shell implements basic file operations (SED edit, awk match)
【JetCache】JetCache的配置说明和注解属性说明
Preview word documents online
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
[jetcache] jetcache configuration description and annotation attribute description