rust_learning/
package_crate_use.rs

1mod back_of_house {
2    // 这个结构体需要提供一个公共的关联函数来构造 Breakfast 的实例 (这里我们命名为 summer)。
3    // 如果 Breakfast 没有这样的函数,我们将无法在 eat_at_restaurant 中创建 Breakfast 实例,
4    // 因为我们不能在 eat_at_restaurant 中设置私有字段 seasonal_fruit 的值。
5    pub struct Breakfast {
6        pub toast: String,
7        seasonal_fruit: String,
8    }
9    impl Breakfast {
10        pub fn summer(toast: &str) -> Breakfast {
11            Breakfast {
12                toast: String::from(toast),
13                seasonal_fruit: String::from("peaches"),
14            }
15        }
16    }
17    // 如果我们将枚举设为公有,则它的所有成员都将变为公有。
18    pub enum Appetizer {
19        Soup,
20        Salad,
21    }
22}
23
24fn eat_at_restaurant() {
25    // 创建一个变量,并使用结构体初始化它。
26    let mut meal = back_of_house::Breakfast::summer("Rye");
27    // 改变变量的值
28    meal.toast = String::from("Wheat");
29    println!("I'd like {} toast please", meal.toast);
30
31    // 不能修改结构体的字段,因为其字段是私有的。
32    // meal.seasonal_fruit = String::from("blueberries");
33
34    //创建一个变量,并使用结构体初始化它。
35}
36
37
38pub mod a {
39    pub mod b {
40        pub fn test_use_() {}
41    }
42}
43
44// 注意 use 只能创建 use 所在的特定作用域内的短路径。
45// use crate::package_crate_use::a::b;
46mod customer {
47    // 将 use 移动到 customer 模块内,
48    use crate::package_crate_use::a::b;
49    pub fn test_use_() {
50        // use of undeclared crate or module `b`
51        b::test_use_();
52        // 或者在子模块 customer 内通过 super::a::b 引用父模块中的这个短路径。
53        super::a::b::test_use_();
54    }
55}
56
57
58use std::fmt::Result;
59// 使用 as 指定一个新的本地名称或者别名。
60use std::io::Result as IoResult;
61
62fn function1() -> Result {
63    // --snip--
64    Ok(())
65}
66
67fn function2() -> IoResult<()> {
68    // --snip--
69    Ok(())
70}