前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rust修仙笔记结丹期

Rust修仙笔记结丹期

作者头像
Maic
发布2024-06-17 12:39:43
810
发布2024-06-17 12:39:43
举报
文章被收录于专栏:Web技术学苑Web技术学苑
本文主要记录rust学习中的一些代码片段,rust语言学习有点像大杂烩,零碎的知识很多,有点集ts,go,c++大成。本文是一篇rust学习笔记,希望看完有所帮助。

切片

将数组或者字符串进行截取操作

代码语言: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 带字段的
代码语言:javascript
复制
 
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
代码语言:javascript
复制
 
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
代码语言:javascript
复制
 
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 元组
代码语言:javascript
复制
 
struct Info(i32, f32);
fn main() {
   let stu_info = Info(18, 20.1);
    println!("stuInfo: {}, {}", stu_info.0, stu_info.1);
}
  • 解构元组
代码语言:javascript
复制
 
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创建一个枚举类型,可以是带字段的,也可以是元组

代码语言:javascript
复制
 
#[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

代码语言:javascript
复制
 
let num = Some(1);

let num2 = if let Some(1) == num {
  println!("{}", num);
} else {
};
println!("{}", num2);

fn

rust中申明一个函数的方式几种

  • 通过|i|i;方式
代码语言:javascript
复制
 
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);
}
  • 无返回值
代码语言:javascript
复制
 
fn fizebuzee_to(n:u32) ->() {
     println!("n={}", n);
    for item in 1..=n {
        println!("{}", item);
    }
}
//or

fn fizebuzee_to2() {
  println!("call function")
}
  • 有返回值,没有分号,直接返回
代码语言:javascript
复制
 
fn test1() -> u32 {
}

等价于下面

代码语言:javascript
复制
 
fn test2() -> u32 {
    return 100;
}

use

使用一个别名替代完整访问mod模块方法名

代码语言:javascript
复制
 
mod deeply {
    pub mod nested {
        pub fn test() {
            println!("hello test")
        }
    }
}

fn main() {
  deeply::nested::test(); // hello test
}

当我们使用use简写后

代码语言:javascript
复制
 
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可以访问当前模块的父级

代码语言:javascript
复制
 
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)

代码语言:javascript
复制
 
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.rsmy模块,在main中调用,我们先以简单例子来看下

代码语言:javascript
复制
 
// main.rs
pub mod my {
    pub fn my_function() {
        println!("Hello from my!");
    }
}
fn main() {
    my::my_function(); // 调用 my 模块的 my_function 函数
}

如果我想把my模块拆分出来

代码语言:javascript
复制
 
// my.rs
 pub fn my_function() {
   println!("Hello from my!");
}

main.rs中引入

代码语言:javascript
复制
 
mod my;
fn main() {
    my::my_function(); // 调用 my 模块的 my_function 函数
}

rust中提供了强大的模块系统,模块内部可以是函数结构体traidimpl块,还可以是其他模块。

代码语言:javascript
复制
 
// 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

代码语言:javascript
复制
 
// 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

代码语言:javascript
复制
 
// 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

代码语言:javascript
复制
 
// 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中引入

代码语言:javascript
复制
 
// 引入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划分模块,我们可以将函数traitimpl放在mod中,如何引入mod
  • code example

最后,看完觉得有收获的,点个赞,在看,转发,收藏等于学会,原创不易,欢迎关注Web技术学苑,好好学习,天天向上!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-06-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Web技术学苑 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 切片
  • struct
  • 枚举
  • Option枚举
  • fn
  • use
  • pub and mod
  • 泛型
  • 关联类型
  • trait
  • mod 模块文件拆分
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档