Rust 组织管理
概述
Rust 的模块系统帮助你组织代码。
📦 模块定义
rust
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
front_of_house::hosting::add_to_waitlist();
}继续学习:下一章 - Rust 泛型与特性
Rust 泛型与特性
概述
泛型和特性是 Rust 强大的抽象工具。
🔧 泛型函数
rust
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}🎯 特性定义
rust
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
pub headline: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}: {}", self.headline, self.content)
}
}继续学习:下一章 - Rust 文件与 IO
Rust 文件与 IO
概述
Rust 提供了强大的文件和 IO 操作功能。
📁 文件读取
rust
use std::fs;
fn main() {
let contents = fs::read_to_string("hello.txt")
.expect("Something went wrong reading the file");
println!("With text:\n{}", contents);
}📁 文件写入
rust
use std::fs;
fn main() {
fs::write("hello.txt", "Hello, world!")
.expect("Unable to write file");
}继续学习:下一章 - Rust 集合与字符串
Rust 集合与字符串
概述
Rust 标准库包含许多有用的集合类型。
📚 Vector
rust
fn main() {
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2];
println!("The third element is {}", third);
}📚 字符串
rust
fn main() {
let mut s = String::new();
let data = "initial contents";
let s = data.to_string();
let s = String::from("initial contents");
let mut s = String::from("foo");
s.push_str("bar");
println!("{}", s);
}📚 HashMap
rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let team_name = String::from("Blue");
let score = scores.get(&team_name);
println!("{:?}", score);
}继续学习:下一章 - Rust 面向对象