十分钟 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()
}

本文完,感谢阅读

相关推荐
ai小鬼头1 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
漂流瓶jz1 小时前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
前端 贾公子1 小时前
在移动端使用 Tailwind CSS (uniapp)
前端·uni-app
散步去海边1 小时前
Cursor 进阶使用教程
前端·ai编程·cursor
清幽竹客1 小时前
vue-30(理解 Nuxt.js 目录结构)
前端·javascript·vue.js
weiweiweb8881 小时前
cesium加载Draco几何压缩数据
前端·javascript·vue.js
幼儿园技术家1 小时前
微信小店与微信小程序简单集成指南
前端
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试