当前位置:网站首页>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 .
边栏推荐
- Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
- About the practice topic of screen related to unity screen, unity moves around a certain point inside
- 微信小程序获取某个元素的信息(高、宽等),并将px转换为rpx。
- Shell 实现文件基本操作(sed-编辑、awk-匹配)
- 2022上半年值得被看见的10条文案,每一句都能带给你力量!
- Basic 10 of C language: array and pointer
- Is there a specific format for English papers?
- Cmake basic use
- v8
- Centos7 one click compilation to build MySQL script
猜你喜欢
![[shutter] Introduction to the official example of shutter Gallery (learning example | email application | retail application | wealth management application | travel application | news application | a](/img/f2/f3b8899aa774dd32006c5928d370f1.gif)
[shutter] Introduction to the official example of shutter Gallery (learning example | email application | retail application | wealth management application | travel application | news application | a

奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
![Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration](/img/a3/55bb71d39801ceeee421a0c8ded333.png)
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration

Linux软件:如何安装Redis服务

Introduction of UART, RS232, RS485, I2C and SPI

An excellent orm in dotnet circle -- FreeSQL

Install docker and use docker to install MySQL

MySQL 23道经典面试吊打面试官

ftrace工具的介绍及使用

Where can I find the English literature of the thesis (except HowNet)?
随机推荐
FRP reverse proxy +msf get shell
Nc20806 District interval
NC24840 [USACO 2009 Mar S]Look Up
Understanding and application of least square method
Redis21 classic interview questions, extreme pull interviewer
Extension of flutter
The "2022 China Digital Office Market Research Report" can be downloaded to explain the 176.8 billion yuan market in detail
[target detection] r-cnn, fast r-cnn, fast r-cnn learning
Kubernetes simple introduction to writing YML
[jetcache] jetcache configuration description and annotation attribute description
What is the standard format of a 2000-3000 word essay for college students' classroom homework?
What website can you find English literature on?
Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
毕业总结
线程的启动与优先级
MySQL 23 classic interview hanging interviewer
腾讯云免费SSL证书扩展文件含义
Sysdig analysis container system call
[IELTS reading] Wang Xiwei reading P1 (reading judgment question)
Introduction and use of ftrace tool