Learning-Rust.Github.io:面向所有人的 Rust 编程语言教程

Hacker News Top 产品

摘要

一个免费的在线资源,提供带有代码示例的 Rust 编程语言教程,使用 Hugo 和 Pagefind 构建。

暂无内容
查看原文
查看缓存全文

缓存时间: 2026/08/04 13:45

# 学习 Rust 来源:https://learning-rust.github.io/ 面向所有人的 Rust 编程语言教程! ## 数据与行为 ```rust struct Person { name: String, company_name: String, } impl Person { fn new(name: String, company_name: String) -> Self { Self { name, company_name } } fn intro(&self) -> String { format!("I'm {} from {}", self.name, self.company_name) } } trait Greet { const PREFIX: &'static str = "Hello"; fn greet(&self) -> String { format!("{}!", String::from(Self::PREFIX)) } } impl Greet for Person {} fn main() { let steve = Person::new("Steve".to_string(), "Apple".to_string()); println!("{}", steve.greet()); // Hello! println!("{}", steve.intro()); // I'm Steve from Apple } ``` ## 函数式 ```rust fn main() { let marks = ["10", "20", "30", "0.4", "0.5", "invalid"]; let sum: i32 = marks // 遍历 marks .iter() // 将字符串解析为浮点数,忽略无效值 .filter_map(|&s| s.parse::<f32>().ok()) // 将小于 1.0 的小数乘以 100 .map(|num| if num < 1.0 { num * 100.0 } else { num }) // 追踪中间值 .inspect(|&val| println!("Parsed: {val}")) // 将浮点数转换为整数 .map(|num| num as i32) // 聚合 .sum(); println!("Final: {sum}"); // 150 } ``` ## 高级蓝图 ```rust use std::collections::HashMap; enum Data<K, V> { Value(V), KeyValue(K, V), } fn main() { let data = vec![ Data::KeyValue("Steve", 10), Data::Value(20), Data::KeyValue("Bill", 30), Data::Value(40), ]; let map = data .into_iter() // 模式匹配与解构 .map(|item| match item { Data::KeyValue(k, v) => { println!("{k}: {v}"); (k.to_string(), v) } Data::Value(v) => { println!("unknown: {v}"); ("unknown".to_string(), v) } }) // 将条目累计到 map 中 .fold(HashMap::new(), |mut map, (key, value)| { map.entry(key) .and_modify(|existing| *existing += value) .or_insert(value); map }); println!("Map: {:?}", map); // Map: {"unknown": 60, "Bill": 30, "Steve": 10} } ``` ### GoHugo 全球最快的网站构建框架。 ### Pagefind 完全静态的搜索库,旨在大型站点上也能有良好表现。 ### e25DX 现代化、模块化的技术文档与博客搭建方案。 ### 文档 帮助我们改进文档。

相似文章

Google 的 Rust 代码风格指南

Lobsters Hottest

Google 发布了官方的 Rust 风格指南,涵盖代码组织、导入、格式化、所有权/借用模式、API 设计以及类型约定,旨在 Google 的规模下编写符合 Rust 惯用风格的代码。

Turbofish 的堡垒

Lobsters Hottest

这是 Rust 编程语言的主要源代码仓库,详细介绍了其性能、可靠性和生产力等特性,以及安装、贡献和工具信息。