likes
comments
collection
share

十分钟 Rust 入门

作者站长头像
站长
· 阅读数 50

前言

随着 Rust 在前端领域的使用越来越广,作为前端工程师有必要学习 Rust 这门语言了

十分钟 Rust 入门

变量赋值

// 不可变
let foo: i32 = 1;
// 可变
let mut bar: i32 = 1;

基础数据类型

整数

长度有符号无符号
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

浮点数

// f32
let foo: f32 = 1.32;
// f64
let bar: f64 = 1.64;

布尔值

// bool
let foo = true;
let bar = false;

字符

// char
let char = 'a';

复合数据类型

字符串和切片

// String
let hello = String::from("Hello");
// slice
let a = &hello[1..5];

数组

// 长度固定
let arr: [i32; 5] = [1, 2, 3, 4, 5];

元组

// tuple
let tup: (i32, &str, f64) = (1, "a", 3.2);

枚举

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

结构体

// struct
struct User {
    name: String,
    age: i32,
}

let user = User {
    name: String::from("mike"),
    age: 24,
};

集合类型

向量

// 长度可变
let vec: Vec<i32> = vec![1, 2, 3, 4, 5];

哈希表

use std::collections::HashMap;
// HashMap
let mut map: HashMap<&str, &str> = HashMap::new();
map.insert("foo", "bar");

模式匹配

let dir = Direction::Right;

match dir {
    Direction::Down => println!("down"),
    Direction::Left => println!("left"),
    _ => println!("other"),
}

分支语句

let a = 60;

if a > 50 {
    println!("大于 50");
} else if a < 50 {
    println!("小于 50");
} else {
    println!("等于 50");
}

循环语句

loop for while

let mut a = 100;

while a > 0 {
    a -= 1;
}

for v in 0..10 {
    println!("{}", v);
}

loop {
    println!("loop")
}

函数

fn hello(name: &str) {
    println!("Hello, {}", name);
}

fn main() {
    hello("John");
}

闭包

 let add_one = |x: u32| -> u32 { x + 1 };

模块

mod my_mod {
    pub fn hello() {
        println!("Hello");
    }
}

use my_mod::hello;

fn main() {
    hello()
}

本文完,感谢阅读

转载自:https://juejin.cn/post/7296384298901880841
评论
请登录