一、基本語法
Rust語言是一門用於可靠性、安全性和並發性的現代編程語言。它的語法靈活,支持函數定義、循環、if語句等。Rust有兩種函數語法:函數聲明和函數定義:
fn main() {
println!("Hello, world!");
}
Rust中的變量默認是不可變的,如果需要定義可變變量,需要使用mut關鍵詞:
let mut x = 5;
x = 6;
Rust的控制流語句包括if、while和for循環:
fn main() {
let x = 5;
let y = if x == 5 { 10 } else { 15 };
println!("{}", y);
let mut i = 0;
while i < 5 {
println!("i = {}", i);
i += 1;
}
let a = [1, 2, 3, 4, 5];
for element in a.iter() {
println!("{}", element);
}
}
二、所有權和借用
Rust的所有權機制確保內存安全,不會出現空指針、野指針等問題。在Rust中,每個值都有一個變量,稱為所有者。任何時候,只能有一個所有者。如果所有權轉移,那麼所有權將從舊的所有者移動到新的所有者:
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1); // 錯誤,s1的所有權已經轉移給了s2
println!("{}", s2); // 輸出:hello
}
Rust還提供了借用機制,允許臨時借用變量的所有權,而不是將所有權轉移給函數或方法:
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("The length of '{}' is {}.", s, len);
}
三、模塊化編程
Rust允許將代碼分為多個模塊,以便更好地組織和管理代碼。可以使用mod關鍵詞定義模塊,一個模塊可以包含多個子模塊:
mod my_module {
mod sub_module {
fn sub_function() {
println!("Sub function");
}
}
pub fn my_function() {
println!("My function");
sub_module::sub_function();
}
}
fn main() {
my_module::my_function();
}
四、生命周期
Rust的內存安全是通過生命周期機制來實現的,生命周期描述了變量的生命周期,確保任何引用始終指向有效的內存。生命周期使用’標記來聲明,生命周期必須滿足引用的範圍的要求:
fn longest(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is {}.", result);
}
五、並發編程
Rust提供了基於線程的並發編程支持。Rust的並發編程機制使用通道(Channel)和消息傳遞來實現線程間的通信。通道分為同步通道和異步通道,同步通道用於在線程之間進行同步,異步通道用於保持線程之間的獨立性:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("{}", received);
}
六、Futures和異步編程
Rust的futures和異步編程支持使異步編程變得容易。Future表示一個可能完成或失敗的異步操作,因此可以創建和組合Future來實現異步代碼的編寫:
use futures::future::Future;
use futures::executor::block_on;
async fn hello_world() {
println!("hello, world!");
}
fn main() {
let future = hello_world();
block_on(future);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/186373.html