Home

rustlings-generics

generics1 // This shopping list program isn't compiling! // Use your knowledge of generics to fix it. // Execute `rustlings hint generics1` for hints! fn main() { let mut shopping_list: Vec<?> = Vec::new(); shopping_list.push("milk"); } 每一个编程语言都有高效处理重复概念的工具。在Rust中其工具之一就是泛型。泛型是具体类型或其他属性的抽象替代。Vec是泛型容器,我们在<>里面填上适合的类型即可。这里填入&...

Read more

rustlings-error_handling

errors1 // errors1.rs // This function refuses to generate text to be printed on a nametag if // you pass it an empty string. It'd be nicer if it explained what the problem // was, instead of just sometimes returning `None`. The 2nd test currently // does not compile or pass, but it illustrates the behavior we would like // this function to have...

Read more

rustlings-string

string1 // strings1.rs // Make me compile without changing the function signature! // Execute `rustlings hint strings1` for hints ;) fn main() { let answer = current_favorite_color(); println!("My current favorite color is {}", answer); } fn current_favorite_color() -> String { "blue" } 之前的例子里我们提到过这个问题。Rust的核心语言中只有一种字符串类型:str。...

Read more

rustlings-collections

vec1 // vec1.rs // Your task is to create a `Vec` which holds the exact same elements // as in the array `a`. // Make me compile and pass the test! // Execute the command `rustlings hint vec1` if you need hints. fn array_and_vec() -> ([i32; 4], Vec<i32>) { let a = [10, 20, 30, 40]; // a plain array let v = // TODO: declare you...

Read more

rustlings-modules

Rust的模块系统: 包:Cargo 的一个功能,它允许你构建、测试和分享 crate。 Crates:一个模块的树形结构,它形成了库或二进制项目。 模块和use:允许你控制作用域和路径的私有性。 路径:一个命名例如结构体、函数或模块等项的方式 module1 // modules1.rs // Make me compile! Execute `rustlings hint modules1` for hints :) mod sausage_factory { fn make_sausage() { println!("sausage!"); } } fn main() { sausage_factory::mak...

Read more

链表

use List::*; enum List { //Cons:元组结构体,包含链表的一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), //Nil:末结点,表明链表结束 Nil, } //可以为 enum 定义方法 impl List { //创建一个空的 List 实例 fn new() -> List { //`Nil` 为 `List` 类型(译注:因 `Nil` 的完整名称是 `List::Nil`) Nil } //处理一个 List,在其头部插入新元素,并返回该 List fn prepend(self, elem: u...

Read more

rustlings-enum

enum1 // enums1.rs // Make me compile! Execute `rustlings hint enums1` for hints! #[derive(Debug)] enum Message { // TODO: define a few types of messages as used below } fn main() { println!("{:?}", Message::Quit); println!("{:?}", Message::Echo); println!("{:?}", Message::Move); println!("{:?}", Message::ChangeColor); } ...

Read more

专题(Display和Debug)

我们具体来说说前面屡次出现的#[derive(Debug)]。 所有的类型,若想用std::fmt的格式化打印,都要求实现至少一个可打印的traits。自动的实现只为一些类型提供,比如std库中的类型。所有其他类型都必须手动实现。fmt::Debug这个trait使这项工作变得相当简单。所有类型都能推导(derive)fmt::Debug的实现。但是fmt::Display需要手动实现。 所有std库类型都天生可以使用{:?}来打印,不过,使用derive的一个问题是不能控制输出的形式。而且也会牺牲一些美感。我们可以通过{:#?}来美化打印。 //`derive`属性会自动创建所需的实现,使这个`struct`能使用 `fmt::Debug`打印。 #[derive(Debug)]...

Read more