每日一文之rust初探

2022-05-05 11:56:49 浏览数 (1)

笔者目前接触到的编程语言有java php python golang c/c lua scala erlang。

最近在了解rust,怎样通过rust去构建业务系统呢。

使用rust的理由

  • 无gc
  • 内存安全,编译器强大
  • 零成本抽象,你不必为你的抽象付出一些额外的代价,因为编译器帮你做了,不会在运行时产生额外的开销

安装

  • curl http://sh.rustup.rs -sSf | sh 更新 rustup update

和其他语言一样,支持基本的类型

  • i8 i16 i32 i64 i128
  • f32 f64 T,N str (T,U) fn(i32) -> i32

变量声明的类型在后面,前面需要加上:。比如 let mut I1:u8 = 12321

变量申明使用let,变量默认不可变,可变需要关键字mut

函数 fn开头

支持闭包

支持字符串&str(栈)和String(堆)

支持条件判断 if while for

支持match有点像switch

支持自定义类型 tuple,struct

支持enum,enum可以支持多种不同的类型,这点很有用

通过定义struct或者enum,代码impl xxx 实现类似类的定义

支持包的管理 module import use

支持各类集合 list array slice hashmap

附上一些练习代码

代码语言:rust复制
use std::env;
use std::collections::HashMap;


fn add(a :u64, b :u64)-> u64 {
    a   b
}

fn req_status() -> u32 {
    400
}


#[derive(Debug)]
struct Ai;

struct Color(u8,u8,u8);
struct People{
    name:String,
    age:u8,
    weight:u8,
}

impl People {
    fn new(name: &str, age:u8, weight:u8) -> People {
        People{
            name :name.to_string(),
            age :age,
            weight :weight
        }
    }

    fn get_age(&self) -> u8 {
        self.age
    }

    fn set_age(&mut self, age: u8) {
        self.age = age
    }

}


enum Shape {
    Clz {
        name :String
    },
    S2{
        location:String,
        timestamp:u64
    }
}


fn main() {

    let str1 = env::args().skip(1).next();

    match str1 {
        Some(str1) => println!("hi {}", str1),
        None => panic!("match failed")
    }

    let name = "tom";
    println!("my name is {}", name);

    let add_result =  add(321, 114);
    println!(" 321   114 = {}",add_result);


    let sqx = |x| x * x;
    let twice = sqx(5);
    let b_closure = |b, c|{
        let z = b   c;
        z * twice
    };
    println!("xx={}", b_closure(1,1));

    
    let str2: String = "bobo".to_string();
    let str3 = String::from("this is str3");
    println!("{},{}", str2, str3);

    let a = 12;
    if a > 12 {
        println!("a is big then 12")
    } else {
        println!("a is not big then 12")
    }
    let result = if 1 == 2 {
        "1 == 2"
    }else {
        "1 != 2"
    };
    println!("result={}", result);


    let status = req_status();
    match status {
        200 => println!("success"),
        400 => println!("found failed"),
        other => {
            println!("other code={}", other);
        }
    }

    let mut x = 3;
    'increment: loop {
        if x <  0 {
            break 'increment;
        }
        println!("x={}",x);
        x -= 1;
    } 
    let mut x = 3;
    while x > 0 {
        println!("x={}",x);
        if x <  0 {
            break ;
        }
        x -= 1;
    }


    let ai = Ai;
    let color1 = Color(255,255,255);
    println!("{},{},{}", color1.0, color1.1, color1.2);
 

    let people = People{
        name:"tom".to_string(),
        age:12,
        weight:100
    };
    println!("{},{},{}", people.name, people.age, people.weight);

    
    let shape1 = Shape::Clz{
        name:"tim".to_string(),
    };

    match shape1 {
        Shape::Clz{name} => {
            println!("name= {}", name);
        },
        Shape::S2{location,timestamp} => {
            println!("location= {}", location);
        },
        _ => {
            println!("other")
        }
    }
    

    let p2 = People::new("tom", 12, 100);
    println!("{},{},{}", p2.name, p2.age, p2.weight);


    //集合
    //array
    let numbers:[u8;10] = [1,2,3,4,5,6,7,8,9,11];
    let floats = [0.3f64,0.5,0.111];
    println!("floats[1]:{}", numbers[1]);
    println!("floats[1]:{}", floats[1]);
    //tuple
    let i_i_str :(u8,u8, &str) = (40,12, "hi");
    println!("{:?}", i_i_str);
    //list
    let mut list1:Vec<u8> = Vec::new();
    list1.push(1);
    list1.push(2);
    println!("idx1={}", list1[1]);

    //hash
    let mut hash1 = HashMap::new();
    hash1.insert("a", 1);
    hash1.insert("b", 2);
    for (k,v) in &hash1{
        println!("i got {}={}", v, k);
    }
    //slice
    let mut ns:[u8;4] = [1,2,3,4];
    let step2:&[u8] = &ns[0..2];
    println!("{:?}", step2);



}

0 人点赞