Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

编程语言

Rust 借用、字符串修改与区间边界 | Elysia Tools

用明确输入与可独立核对的结果,完成三个范围有限的 Rust 练习。

案例

这个案例集合中的条目

代码rust简单

Rust Hello World

Rust Hello World程序和基本语法,包含所有权概念

难度

3/10

预计时间

15 min

标签

rust, systems programming, ownership

前置条件

Basic programming concepts

rust
// Rust Hello World Examples

// 1. Basic Hello World
fn main_basic() {
    println!("Hello, World!");
}

// 2. Hello World with variable binding
fn main_with_variable() {
    let message = "Hello, World!";
    println!("{}", message);
}

// 3. Hello World with function
fn say_hello() -> &'static str {
    "Hello, World!"
}

fn main_with_function() {
    println!("{}", say_hello());
}

// 4. Hello World with ownership demonstration
fn main_with_ownership() {
    let s1 = String::from("Hello");
    let s2 = s1; // s1 is moved to s2
    // println!("{}", s1); // This would cause a compile error
    println!("{} World!", s2);
}

// 5. Hello World with borrowing
fn main_with_borrowing() {
    let s1 = String::from("Hello");
    let len = calculate_length(&s1); // borrow s1
    println!("Length of '{}' is {}.", s1, len); // s1 is still valid
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

// 6. Hello World with mutable borrowing
fn main_with_mutable_borrowing() {
    let mut s = String::from("Hello");
    change(&mut s);
    println!("{}", s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", World!");
}

// 7. Hello World with struct
struct Greeting {
    message: String,
}

impl Greeting {
    fn new(message: &str) -> Greeting {
        Greeting {
            message: message.to_string(),
        }
    }

    fn display(&self) {
        println!("{}", self.message);
    }
}

fn main_with_struct() {
    let greeting = Greeting::new("Hello, World!");
    greeting.display();
}

// 8. Hello World with enum
enum Status {
    Connected,
    Disconnected,
}

fn main_with_enum() {
    let status = Status::Connected;
    match status {
        Status::Connected => println!("Hello, Connected World!"),
        Status::Disconnected => println!("Goodbye, World!"),
    }
}

// 9. Hello World with error handling
use std::fs::File;

fn main_with_error_handling() {
    match File::open("hello.txt") {
        Ok(_file) => println!("Hello, File World!"),
        Err(_error) => println!("Hello, Error World!"),
    }
}

// 10. Hello World with vectors and iteration
fn main_with_vectors() {
    let greetings = vec!["Hello", "Bonjour", "Hola", "Ciao"];

    for greeting in greetings {
        println!("{}, World!", greeting);
    }
}

// Basic data types
fn main_data_types() {
    // Scalar types
    let integer: i32 = 42;
    let float: f64 = 3.14;
    let boolean: bool = true;
    let character: char = '🦀';

    // Compound types
    let tuple: (i32, f64, bool) = (42, 3.14, true);
    let array: [i32; 5] = [1, 2, 3, 4, 5];

    println!("Integer: {}, Float: {}, Boolean: {}, Char: {}", integer, float, boolean, character);
    println!("Tuple: {:?}", tuple);
    println!("Array: {:?}", array);
}

// Control flow
fn main_control_flow() {
    let number = 42;

    if number > 0 {
        println!("Positive number");
    } else {
        println!("Non-positive number");
    }

    // Match statement
    match number {
        0 => println!("Zero"),
        1..=9 => println!("Single digit"),
        _ => println!("Multiple digits"),
    }

    // Loops
    for i in 0..5 {
        println!("Iteration {}", i);
    }
}
代码rust中等

Rust 所有权模式

高级所有权概念、借用和生命周期管理

难度

6/10

预计时间

25 min

标签

rust, ownership, borrowing, memory management

前置条件

Basic Rust syntax, Memory concepts

rust
// Rust Ownership Patterns Examples

// 1. Move semantics with vectors
fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec1; // vec1 is moved to vec2

    // println!("{:?}", vec1); // Error: value borrowed here after move
    println!("{:?}", vec2); // This works
}

// 2. Clone to create deep copy
fn main() {
    let vec1 = vec![1, 2, 3];
    let vec2 = vec1.clone(); // Explicit cloning

    println!("{:?}", vec1); // This works
    println!("{:?}", vec2); // This also works
}

// 3. Copy types
fn main() {
    let x = 5;
    let y = x; // x is copied, not moved

    println!("x = {}, y = {}", x, y); // Both work
}

// 4. Borrowing with functions
fn take_ownership(some_string: String) {
    println!("I own: {}", some_string);
} // some_string goes out of scope and is dropped

fn borrow_string(some_string: &String) {
    println!("I'm borrowing: {}", some_string);
} // some_string is not dropped

fn main() {
    let s1 = String::from("hello");
    take_ownership(s1); // s1 is moved
    // println!("{}", s1); // Error: s1 was moved

    let s2 = String::from("world");
    borrow_string(&s2); // s2 is borrowed
    println!("{}", s2); // s2 is still valid
}

// 5. Mutable borrowing
fn change_string(some_string: &mut String) {
    some_string.push_str(" and more");
}

fn main() {
    let mut s = String::from("hello");
    change_string(&mut s);
    println!("{}", s);
}

// 6. Multiple immutable borrows
fn main() {
    let s = String::from("hello");

    let r1 = &s; // OK
    let r2 = &s; // OK
    let r3 = &s; // OK

    println!("{}, {}, {}", r1, r2, r3);
}

// 7. Dangling references (prevented by compiler)
// fn dangle() -> &String { // This would not compile
//     let s = String::from("hello");
//     &s // s goes out of scope, dangling reference
// }

fn no_dangle() -> String { // This works
    let s = String::from("hello");
    s // ownership is moved out
}

// 8. Struct lifetimes
struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&self) -> i32 {
        3
    }

    fn announce_and_return_part<'a>(&self, announcement: &str) -> &'a str {
        println!("Attention please: {}", announcement);
        self.part
    }
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().expect("Could not find a '.'");

    let i = ImportantExcerpt {
        part: first_sentence,
    };

    println!("Level: {}", i.level());
}

// 9. Slices
fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];

    println!("first word: {}, second word: {}", hello, world);

    let word = first_word(&s);
    println!("first word: {}", word);
}

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

// 10. Smart pointers - Box<T>
fn main() {
    let b = Box::new(5);
    println!("b = {}", b);
}

#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
    println!("{:?}", list);
}
代码rust复杂

Rust 并发模式

现代并发编程,包括线程、async/await和通道

难度

8/10

预计时间

30 min

标签

rust, concurrency, multithreading, async

前置条件

Rust ownership, Basic threading concepts

rust
// Rust Concurrency Examples

use std::thread;
use std::sync::{Arc, Mutex};
use std::time::Duration;

// 1. Basic thread creation
fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

// 2. Joining threads
fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}

// 3. Using move closures with threads
fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}

// 4. Shared state with Arc<Mutex<T>>
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}

// 5. Channels for message passing
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();
        println!("Sent: {}", val);
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

// 6. Multiple producers
fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}

// 7. Async/Await with Tokio (requires tokio crate)
// Add to Cargo.toml: tokio = { version = "1", features = ["full"] }

/*
use tokio;

async fn hello_world() {
    println!("Hello, async world!");
}

#[tokio::main]
async fn main() {
    hello_world().await;
}
*/

// 8. Concurrent HTTP requests with async (requires reqwest and tokio)
/*
use reqwest;
use tokio;

async fn fetch_url(url: &str) -> Result<String, Box<dyn std::error::Error>> {
    let response = reqwest::get(url).await?;
    let body = response.text().await?;
    Ok(body)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let urls = vec![
        "https://api.example.com/users",
        "https://api.example.com/posts",
        "https://api.example.com/comments",
    ];

    let mut handles = vec![];

    for url in urls {
        let handle = tokio::spawn(async move {
            fetch_url(url).await
        });
        handles.push(handle);
    }

    for handle in handles {
        let result = handle.await??;
        println!("Response length: {}", result.len());
    }

    Ok(())
}
*/

// 9. Barrier for thread synchronization
use std::sync::Barrier;
use std::thread;

fn main() {
    let mut handles = vec![];
    let barrier = Arc::new(Barrier::new(5));

    for i in 0..5 {
        let c = Arc::clone(&barrier);
        let handle = thread::spawn(move || {
            println!("before barrier in thread {}", i);
            c.wait();
            println!("after barrier in thread {}", i);
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }
}

// 10. Atomic operations
use std::sync::atomic::{AtomicUsize, Ordering};

fn main() {
    let counter = AtomicUsize::new(0);
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn(|| {
            for _ in 0..1000 {
                counter.fetch_add(1, Ordering::Relaxed);
            }
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Final count: {}", counter.load(Ordering::Relaxed));
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

以下练习使用「Rust Hello World」,只追踪指定代码块;其他卡片涉及不同语言功能和依赖。

选择最小示例

代码集合不是一个完整应用。复制到一次性本地项目之前,先隔离相关函数或类并选择入口。

不要调用相邻的 File::open 示例。main_* 函数需要明确入口;String::len 统计字节而非 Unicode 字符数。

使用方式

  1. 1阅读指定卡片,追踪声明的值。样本页面展示代码,不会替你执行这种语言。

常见失败与 edge cases

  • 结果范围

    下面是从源码推导的预期结果,不是编译器或运行时实测输出。交互输入、时钟、文件、线程、外部服务和框架配置不在这些练习范围内。

示例

1. 追踪 calculate_length

如何使用

在「Rust Hello World」找到 calculate_length,使用 String::from("Hello"); &s1,只依次追踪指定操作,不改变顺序。

结果

预期:5; s1="Hello"。不可变借用不移动字符串;ASCII Hello 为五个字节。

2. 追踪 change

如何使用

在「Rust Hello World」找到 change,使用 String::from("Hello"); &mut s,只依次追踪指定操作,不改变顺序。

结果

预期:Hello, World!。可变借用直接追加调用者的字符串,不返回新字符串。

3. 追踪 main_control_flow

如何使用

在「Rust Hello World」找到 main_control_flow,使用 number=42; 0..5,只依次追踪指定操作,不改变顺序。

结果

预期:Positive number; Multiple digits; indices=0,1,2,3,4。正数分支和通配匹配都适用;循环不包含上界。

专题

JSON 到强类型代码生成器

从 JSON 或 schema 证据生成 TypeScript、Go、Rust、Kotlin、Java、C# 与 Zod 校验模型。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

经典与现代密码工具

在安全的教学或 CTF 场景中比较可逆的经典变换与现代加密,并明确玩具密码不等于安全防护。

专题

文本前后缀与包裹符号批处理,整行整词一次到位

给文本行或词批量添加前后缀,为 SQL、配置和 Markdown 给每个值加引号或反引号包裹,并剥掉粘贴列表带来的编号、符号和装饰。

首页
工具3215
案例593
可视化472
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web194

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

JSON 转 Rust Struct

将 JSON 数据转换为 Rust struct,含 serde Serialize/Deserialize 派生、snake_case 字段与 serde rename 属性

编程语言

Elixir 语言示例

基本的Elixir编程示例,用于并发和分布式系统

编程语言

Zig 示例

Zig编程语言示例 - 简单、高效的系统编程,具有内存安全性