当前位置:网站首页>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 .
边栏推荐
- Array de duplication
- Why is the website slow to open?
- Nacos+openfeign error reporting solution
- Markdown使用教程
- Which software can translate an English paper in its entirety?
- CMake基本使用
- One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
- Basic 10 of C language: array and pointer
- Free we media essential tools sharing
- helm 基础学习
猜你喜欢

What are the recommended thesis translation software?

Introduction and use of ftrace tool
![[target detection] r-cnn, fast r-cnn, fast r-cnn learning](/img/f0/df285f01ffadff62eb3dcb92f2e04f.jpg)
[target detection] r-cnn, fast r-cnn, fast r-cnn learning

Two common methods and steps of character device registration

Why is the website slow to open?

ftrace工具的介绍及使用
![[IELTS reading] Wang Xiwei reading P1 (reading judgment question)](/img/ee/540661fcb2cf1cf1eb15e2026c997a.png)
[IELTS reading] Wang Xiwei reading P1 (reading judgment question)

CMake基本使用

Linux Software: how to install redis service

An excellent orm in dotnet circle -- FreeSQL
随机推荐
Logback configuration file
Confluence的PDF导出中文文档异常显示问题解决
[pulsar document] concepts and architecture
2022上半年值得被看见的10条文案,每一句都能带给你力量!
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
Two common methods and steps of character device registration
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
Where can I check the foreign literature of economics?
Shell脚本基本使用
NC50965 Largest Rectangle in a Histogram
University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
Hundreds of continuous innovation to create free low code office tools
Multiprocess programming (4): shared memory
关于QByteArray存储十六进制 与十六进制互转
FRP reverse proxy +msf get shell
Basic 10 of C language: array and pointer
Nc20806 District interval
Shell 实现文件基本操作(sed-编辑、awk-匹配)
Briefly talk about other uses of operation and maintenance monitoring
数组常用操作方法整理(包含es6)及详细使用