引言
Rust是一种系统编程语言,以其高性能、内存安全和并发性而闻名。本篇文章将提供一系列精选的代码片段,旨在帮助读者轻松入门Rust编程,并逐步进阶。
入门篇
1. Hello, World!
fn main() {
println!("Hello, World!");
}
这是Rust中最基础的程序,用于打印“Hello, World!”到控制台。
2. 变量和数据类型
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The new value of x is: {}", x);
let y: f32 = 5.0;
println!("The value of y is: {}", y);
}
这里展示了如何声明和修改变量,以及如何使用不同的数据类型。
3. 控制流
fn main() {
let number = 3;
if number % 2 == 0 {
println!("{} is even", number);
} else {
println!("{} is odd", number);
}
}
这个例子展示了如何使用if语句进行条件判断。
进阶篇
4. 所有权和借用
fn main() {
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
}
这个例子展示了Rust的所有权系统,其中x
是y
的所有者。
5. 结构体和枚举
struct Rectangle {
width: u32,
height: u32,
}
enum Color {
Red,
Green,
Blue,
}
fn main() {
let rect = Rectangle {
width: 10,
height: 20,
};
println!("Rectangle width: {}, height: {}", rect.width, rect.height);
let color = Color::Red;
println!("Color: {:?}", color);
}
这里展示了如何定义和使用结构体和枚举。
6. 异步编程
#[tokio::main]
async fn main() {
let result = fetch_data().await;
println!("Data fetched: {}", result);
}
async fn fetch_data() -> String {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
"Fetched data".to_string()
}
这个例子展示了如何使用异步编程来处理长时间运行的任务。
实战应用
7. 网络编程
use tokio::net::TcpListener;
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
loop {
let (socket, _) = listener.accept().await.unwrap();
tokio::spawn(async move {
let mut buf = [0; 1024];
let n = socket.read(&mut buf).await.unwrap();
println!("Received: {}", String::from_utf8_lossy(&buf[..n]));
});
}
}
这个例子展示了如何使用Rust创建一个简单的TCP服务器。
8. 游戏开发
struct Vector2 {
x: f32,
y: f32,
}
impl Vector2 {
fn new(x: f32, y: f32) -> Vector2 {
Vector2 { x, y }
}
fn add(&self, other: &Vector2) -> Vector2 {
Vector2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
fn main() {
let v1 = Vector2::new(1.0, 2.0);
let v2 = Vector2::new(3.0, 4.0);
let v3 = v1.add(&v2);
println!("v1 + v2 = ({}, {})", v3.x, v3.y);
}
这个例子展示了如何使用Rust进行游戏开发中的向量运算。
总结
通过这些精选的代码片段,读者可以轻松入门Rust编程,并逐步进阶。Rust是一门强大的编程语言,适用于各种应用场景,包括系统编程、网络编程和游戏开发等。希望这些代码片段能够帮助读者更好地理解和掌握Rust编程。