Rust常用功能實例代碼匯總
通過一系列實用的示例來幫助您更好地理解 Rust 的特性,并展示如何在實際項目中使用這些特性。示例將涵蓋文件操作、網(wǎng)絡(luò)請求、并發(fā)編程、命令行工具以及使用 Cargo 管理依賴等多個方面。
文件操作示例
Rust 提供了強大的標準庫來進行文件操作。在這個示例中,我們將實現(xiàn)一個簡單的文本文件讀寫程序。
創(chuàng)建和寫入文件
我們將使用 std::fs 模塊中的 File 和 Write trait 來創(chuàng)建和寫入文件。
use std::fs::File;
use std::io::{self, Write};
fn write_to_file(filename: &str, content: &str) -> io::Result<()> {
let mut file = File::create(filename)?;
file.write_all(content.as_bytes())?;
Ok(())
}
fn main() {
match write_to_file("output.txt", "Hello, Rust!") {
Ok(_) => println!("File written successfully."),
Err(e) => println!("Failed to write to file: {}", e),
}
}讀取文件
接下來,我們將讀取文件的內(nèi)容并打印到控制臺。
use std::fs::read_to_string;
fn read_from_file(filename: &str) -> io::Result<String> {
let content = read_to_string(filename)?;
Ok(content)
}
fn main() {
match read_from_file("output.txt") {
Ok(content) => println!("File content:\n{}", content),
Err(e) => println!("Failed to read file: {}", e),
}
}網(wǎng)絡(luò)請求示例
Rust 的 reqwest 庫使得發(fā)起 HTTP 請求變得非常簡單。以下示例將演示如何發(fā)送 GET 請求并處理響應(yīng)。
使用 reqwest 庫
首先,確保在 Cargo.toml 中添加 reqwest 依賴:
[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }
tokio = { version = "1", features = ["full"] }發(fā)送 GET 請求
下面的代碼示例演示了如何發(fā)送 GET 請求并處理 JSON 響應(yīng)。
use reqwest::blocking::get;
use reqwest::Error;
use serde::Deserialize;
#[derive(Deserialize)]
struct ApiResponse {
userId: u32,
id: u32,
title: String,
completed: bool,
}
fn fetch_data(url: &str) -> Result<ApiResponse, Error> {
let response = get(url)?.json()?;
Ok(response)
}
fn main() {
let url = "https://jsonplaceholder.typicode.com/todos/1";
match fetch_data(url) {
Ok(data) => println!("Fetched data: {:?}", data),
Err(e) => println!("Error fetching data: {}", e),
}
}并發(fā)編程示例
Rust 提供了內(nèi)置的支持用于并發(fā)編程。在這個示例中,我們將使用 std::thread 模塊創(chuàng)建多個線程并處理數(shù)據(jù)。
創(chuàng)建線程
下面的代碼示例演示了如何創(chuàng)建多個線程,并在每個線程中執(zhí)行計算任務(wù)。
use std::thread;
fn main() {
let mut handles = vec![];
for i in 0..5 {
let handle = thread::spawn(move || {
println!("Thread {} is running", i);
// 模擬計算
i * i
});
handles.push(handle);
}
for handle in handles {
match handle.join() {
Ok(result) => println!("Thread result: {}", result),
Err(e) => println!("Thread error: {:?}", e),
}
}
}使用 Arc 和 Mutex
為了在多個線程間共享數(shù)據(jù),我們可以使用 Arc 和 Mutex 組合。以下示例演示了如何安全地共享和修改數(shù)據(jù)。
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!("Final count: {}", *counter.lock().unwrap());
}數(shù)據(jù)庫操作示例
Rust 也支持與數(shù)據(jù)庫的交互。在這個示例中,我們將使用 diesel 庫進行數(shù)據(jù)庫操作。
設(shè)置 diesel
確保在 Cargo.toml 中添加 diesel 依賴:
[dependencies]
diesel = { version = "1.4", features = ["sqlite"] }創(chuàng)建數(shù)據(jù)庫連接
以下代碼示例演示如何建立與 SQLite 數(shù)據(jù)庫的連接。
#[macro_use]
extern crate diesel;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
fn establish_connection() -> SqliteConnection {
SqliteConnection::establish("my_database.db")
.expect(&format!("Error connecting to {}", "my_database.db"))
}執(zhí)行查詢
以下示例演示了如何執(zhí)行簡單的查詢,并處理結(jié)果。
#[derive(Queryable)]
struct User {
id: i32,
name: String,
}
fn get_users(connection: &SqliteConnection) -> Vec<User> {
use diesel::dsl::insert_into;
use diesel::table;
let results = table::users::table.load::<User>(connection).expect("Error loading users");
results
}
fn main() {
let connection = establish_connection();
let users = get_users(&connection);
for user in users {
println!("User {}: {}", user.id, user.name);
}
}編寫一個簡單的命令行工具
Rust 是編寫命令行工具的理想選擇,因其性能和簡潔性。以下示例將展示如何編寫一個簡單的命令行工具,該工具能夠接收用戶輸入并執(zhí)行基本的文本操作。
創(chuàng)建新項目
首先,我們需要使用 Cargo 創(chuàng)建一個新的項目。打開終端并運行以下命令:
cargo new cli_tool cd cli_tool
編寫命令行工具代碼
我們將在 src/main.rs 中編寫代碼,使其能夠接收用戶輸入并輸出處理后的結(jié)果。以下是一個簡單的命令行工具,它接受用戶輸入的字符串并返回字符串的長度和反轉(zhuǎn)結(jié)果。
use std::io;
fn main() {
println!("請輸入一個字符串:");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("讀取輸入失敗");
let trimmed_input = input.trim();
let length = trimmed_input.len();
let reversed: String = trimmed_input.chars().rev().collect();
println!("您輸入的字符串長度為:{}", length);
println!("反轉(zhuǎn)后的字符串為:{}", reversed);
}運行命令行工具
在終端中運行以下命令,啟動我們的命令行工具:
cargo run
輸入一個字符串,您將看到工具返回該字符串的長度和反轉(zhuǎn)結(jié)果。
使用 Cargo 管理依賴
Cargo 是 Rust 的構(gòu)建系統(tǒng)和包管理器,能夠輕松管理項目依賴。以下示例將展示如何在項目中添加和使用外部庫。
添加依賴
假設(shè)我們想使用 regex 庫來處理正則表達式。在 Cargo.toml 中,添加如下依賴:
[dependencies] regex = "1"
使用外部庫
在 src/main.rs 中,我們將使用 regex 庫進行模式匹配。以下是一個使用正則表達式提取字符串中所有數(shù)字的示例。
use regex::Regex;
use std::io;
fn main() {
println!("請輸入一個字符串:");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("讀取輸入失敗");
let re = Regex::new(r"\d+").unwrap();
let numbers: Vec<&str> = re.find_iter(&input).map(|mat| mat.as_str()).collect();
println!("輸入字符串中的數(shù)字有:{:?}", numbers);
}運行項目
再次使用以下命令運行項目,您將能夠輸入一個字符串,并看到其中提取出的所有數(shù)字。
cargo run
小結(jié)
通過一系列實用示例展示了Rust在文件操作、網(wǎng)絡(luò)請求、并發(fā)編程、命令行工具以及數(shù)據(jù)庫操作等方面的應(yīng)用。這些示例不僅展示了 Rust 的強大功能,還提供了實際開發(fā)中的指導(dǎo)和參考。通過這些示例,您可以更好地理解 Rust 的特性,并將其應(yīng)用于您的項目中。
到此這篇關(guān)于Rust常用功能實例代碼匯總的文章就介紹到這了,更多相關(guān)Rust常用功能示例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用環(huán)境變量實現(xiàn)Rust程序中的不區(qū)分大小寫搜索方式
本文介紹了如何在Rust中實現(xiàn)不區(qū)分大小寫的搜索功能,并通過測試驅(qū)動開發(fā)(TDD)方法逐步實現(xiàn)該功能,通過修改運行函數(shù)和獲取環(huán)境變量,程序可以根據(jù)環(huán)境變量控制搜索模式2025-02-02
Rust中的Iterator和IntoIterator介紹及應(yīng)用小結(jié)
Iterator即迭代器,它可以用于對數(shù)據(jù)結(jié)構(gòu)進行迭代,被迭代的數(shù)據(jù)結(jié)構(gòu)是可迭代的(iterable),所謂的可迭代就是這個數(shù)據(jù)結(jié)構(gòu)有返回迭代器的方法,這篇文章主要介紹了Rust中的Iterator和IntoIterator介紹及應(yīng)用,需要的朋友可以參考下2023-07-07
Rust開發(fā)WebAssembly在Html和Vue中的應(yīng)用小結(jié)(推薦)
這篇文章主要介紹了Rust開發(fā)WebAssembly在Html和Vue中的應(yīng)用,本文將帶領(lǐng)大家在普通html上和vue手腳架上都來運行wasm的流程,需要的朋友可以參考下2022-08-08

