AI搜索

发需求

  • 免费帮选产品
  • 免费帮选企业

Rust编程实战:100个编程练习题

   2025-04-01 10
导读

在Rust编程中,掌握基础语法和高级特性是提高编程技能的关键。以下是100个编程练习题,涵盖了从简单的控制台程序到复杂的数据结构、并发编程和网络编程等方面。

在Rust编程中,掌握基础语法和高级特性是提高编程技能的关键。以下是100个编程练习题,涵盖了从简单的控制台程序到复杂的数据结构、并发编程和网络编程等方面。

1. 基础语法练习题

问题1: 编写一个Rust程序,实现一个简单的加法器,接受两个整数输入并返回它们的和。

```rust

fn main() {

let a = 5;

let b = 3;

println!("{} + {} = {}", a, b, add(a, b));

}

pub fn add(a: i32, b: i32) -> i32 {

a + b

}

```

问题2: 编写一个Rust程序,实现一个函数,该函数接受一个字符串和一个正整数作为参数,然后返回一个新的字符串,其中每个字符都替换为其ASCII码值的平方。

```rust

fn square_ascii_chars(s: &str, n: u32) -> String {

let mut result = String::new();

for c in s.chars() {

result.push(format!("{:x}2", c as u8 * n));

}

result

}

```

问题3: 编写一个Rust程序,实现一个函数,该函数接受一个整数列表,并返回一个新列表,其中包含原始列表中的每个元素的平方。

```rust

fn square_list(nums: Vec) -> Vec {

nums.into_iter().map(|&n| n * n).collect()

}

```

2. 控制台程序练习题

问题4: 编写一个Rust程序,实现一个简单的计算器,接受用户输入的两个数字和一个运算符,然后显示结果。

```rust

fn main() {

let num1 = match input_number("Enter the first number:") {

Ok(num) => num,

Err(e) => e, // error handling for non-numeric input

};

let num2 = match input_number("Enter the second number:") {

Ok(num) => num,

Err(e) => e, // error handling for non-numeric input

};

let operator = match input_operator("Enter the operator (+, -, *, /):") {

Ok(op) => op,

Err(e) => e, // error handling for non-existent operator

};

match (num1, num2, operator) {

(Ok(num1), Ok(num2), Ok(op)) => {

match op {

"+" => println!("The result is {}", add(num1, num2)),

"-" => println!("The result is {}", subtract(num1, num2)),

"*" => println!("The result is {}", multiply(num1, num2)),

"/" => println!("The result is {}", divide(num1, num2)),

_ => panic!("Invalid operator"),

}

},

_ => panic!("Invalid numbers or operators"),

}

}

```

3. 数据结构练习题

问题5: 编写一个Rust程序,实现一个链表节点类,包含添加元素到链表、获取链表头元素和打印链表内容的方法。

```rust

struct Node {

data: T,

next: Option>>,

}

impl Node {

fn new(data: T) -> Self {

Node { data, next: None }

}

}

impl Node {

fn insert(&mut self, data: T) {

if let Some(ref mut node) = self.next {

node.data = data;

node.next = Some(Box::new(self));

} else {

Rust编程实战:100个编程练习题

self.next = Some(Box::new(self));

}

}

fn get_head(&self) -> Option<&T> {

match self.next {

Some(ref mut node) => node.data,

None => None,

}

}

fn print_list(&self) {

match self.next {

Some(ref mut node) => node.print_list(),

None => unreachable!(), // this should never happen in a real program.

}

}

}

```

4. 并发编程练习题

问题6: 编写一个Rust程序,使用`std::sync::mpsc::channel`创建一个生产者-消费者模型,生产者每秒发送一个值给消费者,消费者接收这些值并打印它们。

```rust

use std::sync::mpsc;

use std::thread;

use std::time::Duration;

use std::io::{self, Write};

use std::net::TcpStream;

fn main() {

let (tx, rx) = mpsc::channel();

let mut stream = TcpStream::connect("localhost:8080").unwrap();

let writer = io::BufWriter::with_capacity(1024);

let mut consumer = tx.recv_buf(1024).unwrap();

let producer = loop {

let value = "Hello, world!"; // simulate production of value

consumer.write_all(&[value]).unwrap();

thread::sleep(Duration::from_secs(1)); // simulate delay between messages

};

let producer_thread = thread::spawn(move || {}); // start producer thread

consumer.run(stream.lock()); // start consumer thread on a separate channel to handle received messages

}

```

5. 网络编程练习题

问题7: 编写一个Rust程序,实现一个简单的HTTP服务器,监听端口8080,接受GET请求,并返回"Hello, World!"。

```rust

use std::io::{self, Write};

use std::net::{SocketAddr, TcpListener};

use std::time::Duration;

use tokio::fs;

use tokio::net::TcpListener;

use tokio::net::TcpStream;

use tokio::util;

use tokio::io::{AsyncReadExt, AsyncWriteExt};

use tokio::io::{AsyncReadExt, AsyncWriteExt};

use tokio::net::{SocketAddr, TcpListener};

use tokio::io::{AsyncReadExt, AsyncWriteExt};

use tokio::net::{SocketAddr, TcpListener};

use tokio::io::{AsyncReadExt, AsyncWriteExt};

use tokio::net::{SocketAddr, TcpListener};

use tokio::io::{AsyncReadExt, AsyncWriteExt};

use tokio::net::{SocketAddr, TcpListener};

```

6. 数据流处理练习题

问题8: 编写一个Rust程序,实现一个函数,该函数接受一个整数列表,并返回一个新列表,其中包含每个元素的平方。例如,对于输入[1, 2, 3],应返回[1, 4, 9]。

```rust

fn square_list(nums: Vec) -> Vec {

nums.into_iter().map(|&n| n * n).collect()

}

```

7. 文件操作练习题

问题9: 编写一个Rust程序,读取一个文本文件,将每一行的内容存储在一个字符串向量中,并打印出所有的行。例如,如果文件名为"example.txt",则应该输出:["Hello", "World"]。

```rust

fn main() {

let filename = "example.txt"; // replace with your file name

let contents = fs::read_to_string(filename).expect("Failed to read file");

let lines = contents.lines();

for line in lines {

println!("{}", line); // prints each line from the file

}

}

```

 
举报收藏 0
免责声明
• 
本文内容部分来源于网络,版权归原作者所有,经本平台整理和编辑,仅供交流、学习和参考,不做商用。转载请联系授权,并注明原文出处:https://www.itangsoft.com/baike/show-415381.html。 如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除。涉及到版权或其他问题,请及时联系我们处理。
 
 
更多>热门产品
蓝凌MK 蓝凌MK

123条点评 4.5星

办公自动化

帆软FineBI 帆软FineBI

0条点评 4.5星

商业智能软件

简道云 简道云

0条点评 4.5星

低代码开发平台

纷享销客CRM 纷享销客CRM

105条点评 4.5星

客户管理系统

悟空CRM 悟空CRM

109条点评 4.5星

客户管理系统

钉钉 钉钉

108条点评 4.6星

办公自动化

金蝶云星空 金蝶云星空

117条点评 4.4星

ERP管理系统

蓝凌EKP 蓝凌EKP

0条点评 4.5星

办公自动化

用友YonBIP 用友YonBIP

97条点评 4.5星

ERP管理系统

致远互联A8 致远互联A8

0条点评 4.6星

办公自动化

 
 
更多>同类知识

发需求

免费咨询专家帮您选产品

找客服

客服热线:177-1642-7519

微信扫码添加

小程序

使用小程序 查找更便捷

微信扫码使用

公众号

关注公众号 消息更及时

微信扫码关注

顶部