【Rust编程实战】精选代码片段轻松入门与进阶

日期:

最佳答案

引言

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的全部权体系,其中xy的全部者。

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编程。