Rust 基础速览(二)

Rust 基础速览(二)

  • 结构体和枚举提供实现
  • 集合
  • 小练习


结构体和枚举提供实现

枚举

#[derive(Debug)]
enum Direction {
    N,
    E,
    S,
    W,
}

impl Direction {
    fn next(&self) -> Direction {
        match self {
            Direction::N => Direction::E,
            Direction::E => Direction::S,
            Direction::S => Direction::W,
            Direction::W => Direction::N,
        }
    }
}

fn main() {
    let mut direction = Direction::N;
    println!("{:?}", direction.next());
}

结构体

struct Player {
    name: String,
    age: u8,
}

impl Player {
    fn create_player(name: String, age: u8) -> Player {
        Player { name: name, age: age}
    }
    
    fn get_name(&self) -> &String {
        &self.name
    }
    
    fn set_name(&mut self, name: String) {
        self.name = name;
    }
}

集合

use std::collections::HashMap;

fn main() {
    let numbers: [u8; 5] = [1, 2, 3, 4, 5];

    let tuples: (u8, &str) = (1, "age");

    /// 可增长的数组
    let mut numbers_vec: Vec = Vec::new();
    let mut numbers_vec: Vec = vec![0, 1, 2, 3];
    numbers_vec.push(1);
    let last_number = numbers_vec.pop();

    /// 键值对
    let mut fruits = HashMap::new();
    fruits.insert("apple", 3);
    for (key, value) in &fruits {
        println!("key: {:?}, value: {:?}", key, value);
    }
    fruits.remove("apple");

    /// 切片
    let mut numbers: [u8; 5] = [1, 2, 3, 4, 5];
    let value = &numbers[..];
    println!("numbers: {:?}", &numbers[..]);
    println!("numbers: {:?}", &numbers[0..2]);
}

小练习

判断文本单词数量。

你可能感兴趣的:(Rust,rust,python)