gpt4 book ai didi

struct - 我是否需要始终将基本结构放在 main() 之外以便它们是全局的?

转载 作者:行者123 更新时间:2023-11-29 08:25:06 24 4
gpt4 key购买 nike

我正在阅读 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

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

最佳答案

你不必总是把它们放在something 之外,但你必须在足够高的级别声明它们,以便所有想要使用它的东西都可以看到它,可见性.

通过在 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 }
}
}

关于struct - 我是否需要始终将基本结构放在 main() 之外以便它们是全局的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49610853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com