rust编程入门
由think创建,最终由think 被浏览 30 用户
Rust学习曲线
rust学习过程中的难度曲线。一个字,刺激
开始吧
我用的环境
- mac(其他系统也可以)
 - vscode
 
安装rust
xcode-select --install
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
rustc --version
cargo --version
Hello World in Rust
mkdir rustlearning
cd rustlearning
# rust规范:对于多个单词的文件、目录等使用下划线(_)
mkdir hello_world
cd hello_world
# 启动 vscode,打开当前目录
code .
新建文件 main.rs
fn main() {
    println!("Hello, world!");
}
编译运行
rustc main.rs
./main
- rust和c语言有相似的地方,使用main()做为入口函数,使用{}包含函数体,使用;分割语句
 - rustc是编译器,类似于 gcc
 
\
Cargo - Rust包和构建管理
cargo是rust的包和构建管理工具,类似于 nodejs的npm和python 的 pip。
上面的hello world程序只有一个简单的文件main.rs,也没有外部依赖。但一个来说,一个软件系统,往往很复杂,有很多依赖,这个时候需要用到cargo(默认情况下,cargo会随rust安装)。
➜  rustlearning cargo new hello_cargo
     Created binary (application) `hello_cargo` package
➜  rustlearning ls hello_cargo
Cargo.toml src
cd hello_cargo
# 构建debug版本
cargo build
# 运行
./target/debug/hello_cargo
# 构建并运行,一行代码
cargo run
# cargo check
# 编译release版本
cargo build --release
开发一个猜谜游戏
cargo new guessing_game
cd guessing_game
cargo run
code .
code src/main.rs
src/main.rs
- use,类似于 c 的 include 和 python 的 import
 - std::io 输入输出
 - rand:随机数
 - let secret_number:定义一个不可变值(immutable)变量
 - let mut guess:定义一个可变(mutable)变量
 - String::new 生成一个可变的字符串变量(UTF8),::表示 new 是类型 String 的类函数
 - read_line(&mut guess),&表示传的是引用,mut表示传的可变变量(默认是不可变变量)
 
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
    println!("Guess the number!");
    let secret_number = rand::thread_rng().gen_range(1..101);
    loop {
        println!("Please input your guess.");
        let mut guess = String::new();
        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        println!("You guessed: {}", guess);
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}
可视化Rust的数据类型的内存布局
- 
https://deepu.tech/memory-management-in-rust/
 - 
Rust 中各种数据类型的内存模型(图示版 bilibili)
 
学习资料
\