程序语言 Rust - 用规则减少风险
- https://www.rust-lang.org/
- Performance
- "blazingly fast and memory-efficient" -- like C/C++
- "no garbage collector" -- not like Java
- Reliability
- by rich type system and ownership mode.
- eliminate many classes of bugs at compile-time.
- with a set of rules.
Hello World
fn main() {
println!("Hello, world!"); // call a macro
println("Hello, world 2!"); // call a function
}
Ownership of Value
程序的健壮性,很大一部分来自内存管理。
- explicitly allocate and free the memory
- garbage collection
- check at compile time
- with a set of rules
- through a system of ownership
- in relation to the stack and the heap
- stack is faster
- heap is faster if allocated close together
Ownership Move - The Basic Rule
- Each value has a variable - called its owner.
- There can only be one owner at a time.
- Value is dropped when the owner goes out of scope.
fn main() {
let s1 = String::from("hello");
let (s2, s3) = say_hello(s1); // ownership of s1 moved away
}
fn say_hello(s: String) -> String {
let s3 = String::from("world");
(s, s3) // ownership of s3 moved to caller
}
Reference
通过引用,解决onwership move的问题。
fn say_hello(s: &String) { // ownership is kept through reference
s.push_str(" world"); // not allowed to modify the reference
}
但是改变传进去的变量的值还是有需求的。
fn main() {
let mut s = String::from("hello");
change_hello(&mut s);
}
fn change_hello(s: &mut String) { // ownership is kept
s.push_str(" world"); // modification now allowed
}
- can have only one mutable reference at a specific time
- to avoid race condition
- no restriction on immutable references.
- References must always be valid.
网络资源
- https://github.com/DenisKolodin/yew
- Rust framework for building client web apps