我正在研究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
如果我想用函数构建一个结构,我是否必须通过引用传递基本结构?
答案 0 :(得分:3)
你不必总是将它们放在某些东西之外,但是你必须将它们声明到足够高的水平,以便所有想要使用它的东西都可以看到它,可见性-wise。
通过定义main
函数内部的类型,只有main
函数的主体可以访问它。在这种情况下,是的,您应该将结构的定义放在main
之外,因为main
和build_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 }
}
}