在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
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
fn new(data: T) -> Self {
Node { data, next: None }
}
}
impl
fn insert(&mut self, data: T) {
if let Some(ref mut node) = self.next {
node.data = data;
node.next = Some(Box::new(self));
} else {
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
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
}
}
```