主要参考资料:Rust 程序设计语言
github地址:https://github.com/yunwei37/os-summer-of-code-daily
环境:
uname -a
Linux ubuntu 5.4.0-39-generic #43-Ubuntu SMP Fri Jun 19 10:28:31 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
运行:
curl https://sh.rustup.rs -sSf | sh
Welcome to Rust! Rust is installed now. Great!
重启;
rustc --version
rustc 1.44.1 (c7087fe00 2020-06-17)
很新鲜的样子
查看文档:rustup doc
装了个插件:Rust support for Visual Studio Code
然后跳了个框,说有些组件还没装…
$ mkdir hello_world $ cd hello_world $ cd hello_world
输入:
fn main() { println!("Hello, world!"); } yunwei@ubuntu:~/hello_world$ rustc main.rs yunwei@ubuntu:~/hello_world$ ./main Hello, world! main 函数是一个特殊的函数:在可执行的 Rust 程序中,它总是最先运行的代码。它没有参数也没有返回值。rustfmt 的自动格式化工具正在开发中?我等等去看看Rust 要求所有函数体都要用花括号包裹起来。println! 调用了一个 Rust 宏(macro)。以分号结尾(;),这代表一个表达式的结束和下一个表达式的开始。大部分 Rust 代码行以分号结尾(看起来不是全部)。Cargo 是 Rust 的构建系统和包管理器。
yunwei@ubuntu:~/hello_world$ cargo --version
cargo 1.44.1 (88ba85757 2020-06-11)
yunwei@ubuntu:~$ cargo new hello_cargo Created binary (application) `hello_cargo` package yunwei@ubuntu:~$ cd hello_cargo文件名: Cargo.toml
[package] name = "hello_cargo" version = "0.1.0" authors = ["yunwei <1067852565@qq.com>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] TOML (Tom’s Obvious, Minimal Language) 格式Cargo 期望源文件存放在 src 目录中。项目根目录只存放 README、license 信息、配置文件和其他跟代码无关的文件。使用 Cargo 帮助你保持项目干净整洁,一切井井有条。碰到了这个
yunwei@ubuntu:~/guessing_game$ cargo build Blocking waiting for file lock on package cache解决方法:删除~/.cargo/.package_cache文件,然后 cargo clean ; cargo build
源代码:
use rand::Rng; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); 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 = guess.trim().parse().expect("Please type a number!"); 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; } } } }