最後更新: 2024-08-22
Doc
- https://www.rust-lang.org/learn
- https://doc.rust-lang.org/book
- https://doc.rust-lang.org/rust-by-example/
rustup
Rust is installed and managed by the "rustup" tool
* Rust has a 6-week rapid release process (rustup update)
curl https://sh.rustup.rs -sSf | sh
VS Code Extensions
- rust
- rust-analyzer
Hello World
hello.rs
fn main() { // Print text to the console. println!("Hello World!"); }
* "fn" syntax declares a new function
* main function is special: it is always the first code that runs in every executable Rust program.
* "()" indicate there are no parameters
# Compile
rustc hello.rs
Comments
//
/* ... */
let x = 5 + /* 90 + */ 5;
Variables
let apples = 5;
* In Rust, variables are immutable by default
mutable
let mut bananas = 5; // mutable
bound to
let mut guess = String::new();
"String::new" # a function that returns a new instance of a String
- String type: growable, UTF-8
"::new" # "::" indicates that new is an associated function of the String type
std::io::stdin
Code
use std::io; io::stdin() .read_line(&mut guess) .expect("Failed to read line");
prelude
Rust Prelude = rust 的 buildin 功能
The prelude is the list of things that Rust automatically imports into every Rust program.
It’s kept as small as possible, which are used in almost every single Rust program.
Version
- std::prelude::v1
- std::prelude::rust_2015
- std::prelude::rust_2018
If a type you want to use isn’t in the Rust prelude,
you have to bring that type into scope explicitly with a use statement.
use std::io;
"::"
The double colon (::) is the "path" separator
Paths are comprised of crates, modules, and items
e.g.
crates::modules::items
Call function
io::stdin() .read_line(&mut guess) .expect("Failed to read line");
# std = Rust Standard Library
載入 Library: std, Module: io
Method: read_line()
take whatever the user types into standard input and append that into a string
argument: "&" indicates that this argument is a reference
without needing to copy that data into memory multiple times
&mut arg
references are immutable by default; mut => writable
A.b().c()
# allow break up long lines
io::stdin().read_line(&mut guess).expect("Failed to read line");
error-handling code - ".expect()"
read_line returns a enumeration Result
The Result ’s variants are Ok and Err. If this instance of Result is an Err value,
expect will cause the program to crash and
display the message that you passed as an argument to expect
If you don’t call expect, the program will compile, but you’ll get a warning.