切片
将数组或者字符串进行截取操作
代码语言:javascript复制
fn main () {
let s = String::from("hello word");
let s1 = &s[0..5]; // [..5]
let s2 = &s[6..11]; // [6..]
println!("{},{}", s1,s2);
}
数组进行切换
代码语言:javascript复制
fn main() {
let arr = [1, 2, 3, 4, 5, 6];
let slice = &arr[1..4];
let slice2 = &arr[..4];
let slice3 = &arr[1..];
println!("slice:{:?}", slice); // [2,3,4]
println!("slice2:{:?}", slice2); // [1,2,3,4]
println!("slice3:{:?}", slice3); // [2,3,4,5,6]
}
struct
struct
可以来定义数据类型,可以类比ts
中的interface
- struct 带字段的
struct Stu {
name: String,
age: i32,
}
let user = Stu {
name: String::from("Maic"),
age: 18
}
let user2 = Stu {
name: String::from("Tom"),
..user // ..复制另外一个
}
println!("name:{},age:{}", user.name, user.age);
- 解构struct
struct Stu {
name: String,
age: i32,
}
let user = Stu {
name: String::from("Tom"),
age: 18
}
// 解构user
let Stu {ref name, ref age } = user;
println!("{},{}", name, age);
..
复制另外一个struct
struct Stu {
name: String,
age: i32,
}
let user = Stu {
name: String::from("Maic"),
age: 18
}
let user2 = Stu {
name: String::from("Tom"),
..user // ..复制另外一个
}
println!("name:{},age:{}", user2.name, user2.age);
- struct 元组
struct Info(i32, f32);
fn main() {
let stu_info = Info(18, 20.1);
println!("stuInfo: {}, {}", stu_info.0, stu_info.1);
}
- 解构元组
struct Info(i32, f32);
fn main() {
let stu_info = Info(18, 20.1);
let Info(stu_number, stu_source) = stu_info;
println!("stu_number:{}, stu_score:{}",
stu_number, stu_score);
}
枚举
enum
创建一个枚举类型,可以是带字段
的,也可以是元组
#[warn(dead_code)]
#[derive(Debug)]
enum LoadingStatus {
Loading,
Loaded,
Error,
Pasted(String),
Point { x: i64, y: i64 },
}
fn log(status: LoadingStatus) {
match status {
LoadingStatus::Loading => println!("loading, {:?}", LoadingStatus::Loading),
LoadingStatus::Loaded => println!("loaded"),
LoadingStatus::Error => println!("error"),
LoadingStatus::Pasted(c) => println!("pasted {}", c),
LoadingStatus::Point { x, y } => println!("point {},{}", x, y),
}
}
fn main() {
println!("Hello, world!");
let point = LoadingStatus::Point { x: 1, y: 2 };
let loading = LoadingStatus::Loading;
let pasted = LoadingStatus::Pasted(String::from("Maic"));
log(point);
log(loading);
log(pasted);
}
Option枚举
代码语言:javascript复制
let num1 = Some(1);
enum Option<T> {
Some(T),
None
}
fn main () {
let num = Some(1);
let num2 = plus_one(num);
let v = 0u8;
match v {
1 => 1,
2 => 2,
_ => {
println!("hello, {}", _);
}
}
}
fn plus_one(x:Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i 1)
}
}
用if let
替代match
let num = Some(1);
let num2 = if let Some(1) == num {
println!("{}", num);
} else {
};
println!("{}", num2);
fn
在rust
中申明一个函数的方式几种
- 通过
|i|i;
方式
fn main() {
let diary = |i| i;
println!("{}", diary("i love rust"));
let diary2 = |i: i32| i 1;
println!("{}", diary2(2));
fn diary3(i: i32) -> i32 {
i 1
}
diary3(10);
}
- 无返回值
fn fizebuzee_to(n:u32) ->() {
println!("n={}", n);
for item in 1..=n {
println!("{}", item);
}
}
//or
fn fizebuzee_to2() {
println!("call function")
}
- 有返回值,没有分号,直接返回
fn test1() -> u32 {
}
等价于下面
代码语言:javascript复制
fn test2() -> u32 {
return 100;
}
use
使用一个别名替代完整访问mod
模块方法名
mod deeply {
pub mod nested {
pub fn test() {
println!("hello test")
}
}
}
fn main() {
deeply::nested::test(); // hello test
}
当我们使用use
简写后
use deeply::nested::test as new_test;
mod deeply {
pub mod nested {
pub fn test() {
println!("hello test")
}
}
}
fn main() {
new_test(); // hello test
}
pub and mod
在模块外部无法直接访问模块内部私有方法的,只有被申明的pub
公有方法才能直接访问
self
访问当前模块的方法
super
可以访问当前模块的父级
fn test_maic() {
println!("This is a test maic");
}
mod cool {
mod sub_cool {
// 私有访问
pub fn test_private2() {
println!("This is a private test2");
}
}
// pub申明一个公有的test方法
pub fn test() {
println!("This is a test");
// 私有函数在同一模块内调用
self::test_private();
// 访问内部模块sub_cool,并调用公有函数
self::sub_cool::test_private2();
// cool模块外,使用super调用函数
super::test_maic();
}
// 私有函数,在外部不能直接访问
fn test_private() {
println!("This is a private test");
}
}
fn main() {
println!("Hello, world!");
cool::test();
// cool::test_private(); error 不能访问私有
}
泛型
在方法后面使用通用类型T
,比如fn foo<T: Display>(arg:T){}
struct A
声明了类型A
struct Single(A)
申明类型Single
struct SinglenGen<T>(T)
use std::fmt::Display;
#[derive(Debug)]
struct A;
#[derive(Debug)]
struct Single(A);
#[derive(Debug)]
struct SingleGen<T>(T);
#[derive(Debug)]
struct Years(i64);
fn foo<T: Display>(arg: T) {
println!("{}", arg)
}
impl Years {
pub fn get_year(&self) -> i64 {
self.0
}
}
fn main() {
let age = Years(27);
// `Single` 是具体类型,并且显式地使用类型 `A`。
let _s = Single(A);
// 创建一个 `SingleGen<char>` 类型的变量 `_char`,并令其值为 `SingleGen('a')`
// 这里的 `SingleGen` 的类型参数是显式指定的。
let _char: SingleGen<char> = SingleGen('a');
// `SingleGen` 的类型参数也可以隐式地指定。
let _t = SingleGen(A); // 使用在上面定义的 `A`。
let _i32 = SingleGen(6); // 使用 `i32` 类型。
let _char = SingleGen('a'); // 使用 `char`。
print!("{:?},{:?},{:?},{:?}", _s, _t, _i32, _char);
print!("age:{:?}", age.get_year());
foo("hello word")
}
运行的结果是:
Single(A),SingleGen(A),SingleGen(6),SingleGen('a'),27,hello word
关联类型
代码语言:javascript复制
/**
* 关联类型
*/
struct Container(i32, i32);
trait Contains {
type A;
type B;
}
fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool;
fn first(&self) -> i32;
fn last(&self) -> i32;
}
impl Contains for Container {
type A = i32;
type B = i32;
fn contains(&self, number_1: &Self::A, number_2: &Self::B) -> bool {
(&self.0 == number_1) && (&self.1 == number_2)
}
fn first(&self) -> i32 {
self.0
}
fn last(&self) -> i32 {
self.1
}
}
fn main() {
let c = Container(5, 10);
println!("{}", c.contains(&5, &10));
println!("first:{}", c.first());
println!("last:{}", c.last());
}
trait
代码语言:javascript复制
trait Greet {
fn greet(&self);
}
struct ToDrop;
impl Drop for ToDrop {
fn drop(&mut self) {
println!("ToDrop is being dropped");
}
}
struct Person {
name: String,
}
// impl实现greet具体功能,使用for扩展Person的功能
impl Greet for Person {
fn greet(&self) {
// self可以访问struct Person中的name
println!("Hello, my name is {}!", self.name);
}
}
fn main() {
println!("Hello, world!");
let person = Person {
name: String::from("Alice"),
};
person.greet();
let _x = ToDrop; // 会自动调用drop方法
}
mod 模块文件拆分
我在main.rs
中写了一个main.rs
的my
模块,在main
中调用,我们先以简单例子来看下
// main.rs
pub mod my {
pub fn my_function() {
println!("Hello from my!");
}
}
fn main() {
my::my_function(); // 调用 my 模块的 my_function 函数
}
如果我想把my
模块拆分出来
// my.rs
pub fn my_function() {
println!("Hello from my!");
}
在main.rs
中引入
mod my;
fn main() {
my::my_function(); // 调用 my 模块的 my_function 函数
}
在rust
中提供了强大的模块系统,模块内部可以是函数
、结构体
、traid
、impl
块,还可以是其他模块。
// main.rs
mod my_mod {
fn private_function() {
println!("call my_mod::private_function")
}
// 共有函数
pub fn public_function() {
private_function();
println!("call my_mod::public_function")
}
// 申明了一个OpenBox的struct
pub struct OpenBox<T> {
pub contents: T,
}
// 申明了一个ClosedBox的struct
#[allow(dead_code)]
pub struct ClosedBox<T> {
pub contents: T, // 声明公有
}
impl<T> ClosedBox<T> {
pub fn new(contents: T) -> ClosedBox<T> {
ClosedBox { contents: contents }
}
}
}
fn main() {
my_mod::public_function();
let open_box = my_mod::OpenBox {
contents: "hello Maic",
};
let close_box = my_mod::ClosedBox::new("Best for you");
println!("{}", open_box.contents);
println!("{}", close_box.contents);
}
现在我想把my_mod
模块抽离出去,在src
目录下新建my_mod.rs
// src/my_mod.rs
fn private_function() {
println!("call my_mod::private_function")
}
// 共有函数
pub fn public_function() {
private_function();
println!("call my_mod::public_function")
}
pub struct OpenBox<T> {
pub contents: T,
}
#[allow(dead_code)]
pub struct ClosedBox<T> {
pub contents: T, // 声明公有
}
impl<T> ClosedBox<T> {
pub fn new(contents: T) -> ClosedBox<T> {
ClosedBox { contents: contents }
}
}
然后我们在main.rs
中引入my_mod.rs
// src/main.rs
// my_mod为文件名
mod my_mod;
fn main() {
my_mod::public_function();
let open_box = my_mod::OpenBox {
contents: "hello Maic",
};
let close_box = my_mod::ClosedBox::new("Best for you");
println!("{}", open_box.contents);
println!("{}", close_box.contents);
}
我在src
目录下新建my.rs
我们在nested
这个模块中有公有函数get_hello
,trait
,struct
,还有impl
// src/my.rs
pub mod nested {
pub fn get_hello() {
println!("hello world from nested module")
}
pub trait Hello {
fn say_hello(&self);
}
pub struct HelloMaic;
impl Hello for HelloMaic {
fn say_hello(&self) {
println!("Hello Maic");
}
}
}
在main.rs
中引入
// 引入trait Hello
use my::nested::Hello;
// 会找到my.rs或者my/mod.rs文件
mod my;
fn main() {
my::nested::get_hello();
let maic = my::nested::HelloMaic;
maic.say_hello();
}
总结
- 了解了学习了rust中的切片,如何获取rust中切片数据的截取
- 学习到了
rust
中的自定义数据类型,如何使用struct
创建一个多字段、元组等类型,类比ts中的interface
- 总结了关于
mod
划分模块,我们可以将函数
、trait
、impl
放在mod中,如何引入mod
- code example
最后,看完觉得有收获的,点个赞,在看,转发,收藏等于学会,原创不易,欢迎关注Web技术学苑,好好学习,天天向上!