美文网首页
2022-07-19

2022-07-19

作者: wwmin_ | 来源:发表于2022-07-20 10:10 被阅读0次
  1. vscode快捷键
    ctrl+j 可在编辑区与控制台之间快速切换,在rust变成中验证代码时是很方便的
    ctrl+shift+[ 折叠代码块
    ctrl+shift+] 展开代码块

  2. rust学习
    官网: https://www.rust-lang.org/
    ide: vscode + rust-analyzer + Clippy + Better TOML
    学习网站:

    Rust Learn

https://doc.rust-lang.org/book/
https://github.com/rust-lang/rustlings/
https://doc.rust-lang.org/stable/rust-by-example/

非官方:
https://kaisery.github.io/trpl-zh-cn/title-page.html
https://course.rs/basic/base-type/index.html

  1. 运行rust程序
cargo new demo && cd demo
cargo run
  1. 学习rust的代码
    学习网站: https://course.rs/basic/match-pattern/match-if-let.html
use std::io;
fn main() {
    // base_fn();
    // let s = strin&g();
    // method_arg();
    // ref_num();
    // ref_&string(&s);
    // mut_string();
    // string_oper();
    // slice_oper();
    // str_oper();
    // tup();
    // struct_demo();
    // enum_demo();
    // array_demo();
    match_demo();
}
#[allow(dead_code)]
fn base_fn() {
    // println!("Hello, world!");
    let _y = 10;
    let mut x = 5;
    println!("{}", x);
    x = 6;
    println!("{}", x);

    // println!("{}", _y);

    let (_a, mut _b): (bool, bool) = (true, true);
    println!("a={:?},b={:?}", _a, _b);
    _b = true;
    assert_eq!(_a, _b);

    let (a, b, c, d, e);
    (a, b) = (1, 2);
    [c, .., d, _] = [1, 2, 3, 4, 5];
    Struct { e, .. } = Struct { e: 5 };
    assert_eq!([1, 2, 1, 4, 5], [a, b, c, d, e]);

    const MAX_POINTS: u32 = 100_000;
    let n = MAX_POINTS + 1;
    println!("{}", n);
}
#[allow(dead_code)]
fn string() -> String {
    let s1 = String::from("hello");
    let s2 = s1.clone();
    println!("s1={},s2={}", s1, s2);
    s1
}
#[allow(dead_code)]
fn method_arg() {
    let s = String::from("hello");

    takes_ownership(s);
    // println!("s到这里就失效了:{}", s);

    let x = 5;

    makes_copy(x);
    println!("{}", x);
}
#[allow(dead_code)]
fn takes_ownership(some_string: String) {
    println!("{}", some_string);
}
#[allow(dead_code)]
fn makes_copy(some_interger: i32) {
    println!("{}", some_interger);
}
#[allow(dead_code)]
struct Struct {
    e: i32,
}
#[allow(dead_code)]
fn ref_num() {
    let x = 5;
    let y = &x;

    assert_eq!(5, x);
    assert_eq!(5, *y);
}
#[allow(dead_code)]
fn ref_string(s: &String) -> usize {
    s.len()
}
#[allow(dead_code)]
fn mut_string() {
    let mut s = String::from("hello");
    change(&mut s);

    println!("{}", s);
    fn change(some_string: &mut String) {
        some_string.push_str(",world");
    }
}
#[allow(dead_code)]
fn string_oper() {
    let my_name = "wwmin";
    greet(my_name.to_string());
}
#[allow(dead_code)]
fn greet(name: String) {
    println!("{}", name);
}
#[allow(dead_code)]
fn slice_oper() {
    let s = String::from("hello");
    let len = s.len();
    let _slice = &s[4..len];
    println!("{}", _slice);
    let _slice = &s[4..];
    println!("{}", _slice.to_string());

    let mut ss = String::from("hello world");
    let world = first_world(&ss);

    println!("the first world is: {}", world);
    ss.clear();

    let sss = String::from("hello,world!");
    say_hello(&sss);
    say_hello(&sss[1..]);
    say_hello(&s.as_str());
}
#[allow(dead_code)]
fn first_world(s: &String) -> &str {
    &s[..1]
}
#[allow(dead_code)]
fn say_hello(s: &str) {
    println!("{}", s);
}
#[allow(dead_code)]
fn str_oper() {
    let mut s = String::from("hello ");
    s.push('r'); //操作原始字符串
    println!("{}", s);
    s.push_str("ust!"); //操作原始字符串
    println!("追加字符串 push_str() -> {}", s);

    s.insert(5, ','); //操作原始字符串
    s.insert_str(6, "I like "); //操作原始字符串
    println!("{}", s);

    let string_replace = String::from("I like rust. Learning rust is my favorite!");
    let new_string_replace = string_replace.replace("rust", "c#"); //该方法返回一个新的字符串
    let new_string_replacen = string_replace.replacen("rust", "c#", 1); //该方法返回一个新的字符串
    println!("{}", new_string_replace);
    println!("{}", new_string_replacen);
    println!("{}", string_replace);

    let mut string_range = String::from("I like rust!");
    string_range.replace_range(7..11, "c#"); //操作原始字符串
    eprintln!("string_range = {:?}", string_range);

    // 删除  pop()  remove()  truncate()  clear()
    let mut s_remove = String::from("测试remove方法");
    //删除第一个汉字
    s_remove.remove(0); //操作原始字符串
    eprintln!("s_remove = {:?}", s_remove);
    //删除第二个字
    s_remove.remove(0);
    eprintln!("s_remove = {:?}", s_remove);

    //truncate 截断
    let mut string_truncate = String::from("测试truncate");
    string_truncate.truncate(3); //操作原始字符串
    dbg!(string_truncate);

    //clear
    let mut string_clear = String::from("string clear");
    string_clear.clear(); //操作原始字符串
    dbg!(string_clear);

    // Catenate 连接
    let string_append = String::from("hello ");
    let string_rust = String::from("rust");
    //在下句中,string_append 所有权被转移走了,因此后面不能再使用string_append
    let result = string_append + &string_rust; //返回新的字符串
    let mut result = result + "!";
    result += "!!!";
    dbg!(result);
    // dbg!(string_append);//string_append 所有权被转移走了,故不能继续使用string_append

    //字符串转义
    let byte_escape = "I'm 
        writing
        \x52\x75\x73\x74";
    dbg!(byte_escape);

    for c in "中国人".chars() {
        dbg!(c);
    }
}
#[allow(dead_code)]
fn tup() {
    // let tup: (i32, i32, i32) = (100, 200, 1);
    // let (x, y, z) = tup;
    // dbg!(x, y, z);
    let s1 = String::from("hello");
    let (s2, len) = calculate_length(s1);
    dbg!(s2, len);
}
#[allow(dead_code)]
fn calculate_length(s: String) -> (String, usize) {
    let length = s.len();
    (s, length)
}

#[allow(dead_code)]
#[derive(Debug)]
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

#[allow(dead_code)]
fn struct_demo() {
    let mut user1 = User {
        email: String::from("someone@example.com"),
        username: String::from("someusername"),
        active: true,
        sign_in_count: 1,
    };
    user1.email = "ww@11.com".to_string();
    // dbg!(user1.username);
    dbg!(user1.email);
    let mut user2 = build_user("www@aa.com".to_string(), "wwmin".to_string());
    user2.username = "wwm".to_string();
    dbg!(user2.username);

    let user3 = User {
        email: "ww@11.com".to_string(),
        ..user1
    };
    println!("{:#?}", user3);
    dbg!(user3.email);

    eprintln!("user1.username = {:?}", user2.email);
}

#[allow(dead_code)]
fn build_user(email: String, username: String) -> User {
    User {
        active: true,
        username,
        email,
        sign_in_count: 1,
    }
}

#[allow(dead_code)]
fn enum_demo() {
    let heart = PokerSuit::Clubs;
    print_suit(heart);

    let c1 = PokerCard {
        suit: PokerSuit::Clubs,
        value: 1,
    };
    let c2 = PokerCard {
        suit: PokerSuit::Diamonds,
        value: 12,
    };

    dbg!(c1);
    dbg!(c2);

    let c3 = PokerSuitExt::Spades(5);
    let c4 = PokerSuitExt::Diamonds('A');
    dbg!(c3);
    dbg!(c4);

    let some_number = Some(5);
    let some_string = Some("wwmin");
    //rust中无null值,使用Option<T>().None代替赋值
    let absent_number: Option<i32> = None;
    let six = plus_one(some_number);

    // let res = absent_number + i;
    dbg!(six);

    dbg!(some_number);
    dbg!(some_string);
    dbg!(absent_number);

    let m1 = Message::Quit;
    let m2 = Message::Move { x: 1, y: 1 };
    let m3 = Message::ChangeColor(255, 255, 0);
    dbg!(m1);
    dbg!(m2);
    dbg!(m3);
}

#[allow(dead_code)]
fn print_suit(card: PokerSuit) {
    println!("card = {:?}", card);
}

#[derive(Debug)]
#[allow(dead_code)]
enum PokerSuit {
    Clubs,
    Spades,
    Diamonds,
    Hearts,
}
#[allow(dead_code)]
#[derive(Debug)]
struct PokerCard {
    suit: PokerSuit,
    value: u8,
}
#[allow(dead_code)]
#[derive(Debug)]
enum PokerSuitExt {
    Clubs(u8),
    Spades(u8),
    Diamonds(char),
    Hearts(char),
}

#[allow(dead_code)]
#[derive(Debug)]
enum Message {
    Quit,                       //无关联数据
    Move { x: i32, y: i32 },    //包含一个匿名结构体
    Write(String),              //包含一个String字符串
    ChangeColor(i32, i32, i32), //包含三个i32
}

#[allow(dead_code)]
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

#[allow(dead_code)]
fn array_demo() {
    let a: [i32; 5] = [1, 2, 3, 4, 5];
    println!("Please enter an array index.");
    let mut index = String::new();
    //读取控制台的输出
    io::stdin()
        .read_line(&mut index)
        .expect("Failed to read line");

    let index: usize = index
        .trim()
        .parse()
        .expect("Index entered was not a number");
    let element = a[index];
    println!("The value of the element at index {} is {}", index, element);

    //数组切片
    let slice: &[i32] = &a[1..3];
    assert_eq!(slice, &[2, 3]);
    dbg!(slice);

    let one = [1, 2, 3];
    let two: [u8; 3] = [1, 2, 3];
    let blank1 = [0; 3];
    let blank2: [u8; 3] = [0; 3];
    // arrays是一个二维数组,其中每一个元素都是一个数组,元素类型是[u8; 3]
    let arrays: [[u8; 3]; 4] = [one, two, blank1, blank2];
    // 借用arrays的元素用作循环中
    for a in &arrays {
        print!("{:?}", a);
        // 将a变成一个迭代器,用于循环
        // 你也可以直接用for n in a {}来进行循环
        for n in a.iter() {
            print!("\t{} + 10 = {}", n, n + 10);
        }

        let mut sum = 0;
        for i in 0..a.len() {
            sum += a[i];
        }
        println!("\t({:?} = {})", a, sum);
    }

    for element in a.iter() {
        println!("the value is: {}", element);
    }

    // loop {
    //     println!("again!");
    // }
    let mut counter = 0;
    //loop是一个表达式,因此可以返回一个值
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2; //将值返回,作用类似与return
        }
    };
    println!("The result is {}", result);
}

#[allow(dead_code)]
fn match_demo() {
    let dire = Direction::South;
    match dire {
        Direction::East => println!("East"),
        Direction::North | Direction::South => println!("South or North"),
        _ => println!("West"),
    }
}

#[allow(dead_code)]
enum Direction {
    East,
    West,
    North,
    South,
}

相关文章

网友评论

      本文标题:2022-07-19

      本文链接:https://www.haomeiwen.com/subject/kqajirtx.html