十分钟 Rust 入门

前言

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

变量赋值

rust 复制代码
// 不可变
let foo: i32 = 1;
// 可变
let mut bar: i32 = 1;

基础数据类型

整数

长度 有符号 无符号
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize

浮点数

rust 复制代码
// f32
let foo: f32 = 1.32;
// f64
let bar: f64 = 1.64;

布尔值

rust 复制代码
// bool
let foo = true;
let bar = false;

字符

rust 复制代码
// char
let char = 'a';

复合数据类型

字符串和切片

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

数组

rust 复制代码
// 长度固定
let arr: [i32; 5] = [1, 2, 3, 4, 5];

元组

rust 复制代码
// tuple
let tup: (i32, &str, f64) = (1, "a", 3.2);

枚举

rust 复制代码
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

结构体

rust 复制代码
// struct
struct User {
    name: String,
    age: i32,
}

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

集合类型

向量

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

哈希表

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

模式匹配

rust 复制代码
let dir = Direction::Right;

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

分支语句

rust 复制代码
let a = 60;

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

循环语句

loop for while

rust 复制代码
let mut a = 100;

while a > 0 {
    a -= 1;
}

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

loop {
    println!("loop")
}

函数

rust 复制代码
fn hello(name: &str) {
    println!("Hello, {}", name);
}

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

闭包

rust 复制代码
 let add_one = |x: u32| -> u32 { x + 1 };

模块

rust 复制代码
mod my_mod {
    pub fn hello() {
        println!("Hello");
    }
}

use my_mod::hello;

fn main() {
    hello()
}

本文完,感谢阅读

相关推荐
C澒几秒前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll4 分钟前
学习Three.js–雪花
前端·three.js
onebyte8bits21 分钟前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒30 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC33 分钟前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得01 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice1 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3601 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额2 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a3 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag