我是否需要始终将基础结构放在main()之外,以便它们是全局变量?

时间:2018-04-02 11:57:25

标签: struct rust

我正在研究Rust文档并且正在创建一个带有函数的结构:

fn main() {
    let s1 = String::from("bob");
    let s2 = String::from("bob@aol.com");

    struct User {
        name: String,
        email: String,
    }

    let user1 = build_user(s1, s2); //or &s1, &s2
}

fn build_user(email: String, name: String) -> User {
    //or &String, &String
    User { email, name }
}

错误说:

error[E0412]: cannot find type `User` in this scope
  --> src/main.rs:13:47
   |
13 | fn build_user(email: String, name: String) -> User {
   |                                               ^^^^ not found in this scope

error[E0422]: cannot find struct, variant or union type `User` in this scope
  --> src/main.rs:15:5
   |
15 |     User { email, name }
   |     ^^^^ not found in this scope

如果我想用函数构建一个结构,我是否必须通过引用传递基本结构?

1 个答案:

答案 0 :(得分:3)

你不必总是将它们放在某些东西之外,但是你必须将它们声明到足够高的水平,以便所有想要使用它的东西都可以看到它,可见性-wise。

通过定义main函数内部的类型,只有main函数的主体可以访问它。在这种情况下,是的,您应该将结构的定义放在main之外,因为mainbuild_user都需要知道它:

struct User {
    name: String,
    email: String,
}

fn build_user(email: String, name: String) -> User {
    User { email, name }
}

在阅读时,您将发现编写此代码的惯用方法:

fn main() {
    let s1 = String::from("bob");
    let s2 = String::from("bob@aol.com");

    let user1 = User::new(s1, s2);
}

struct User {
    name: String,
    email: String,
}

impl User {
    fn new(email: String, name: String) -> User {
        User { email, name }
    }
}