在Rust中引用Struct实例中的值时的作用域问题



所以我有了这个程序,一切都按照我的意愿运行。唯一的问题是"student1.name";底部。我想取代";self.name";用";student1.name";,但我有范围界定问题"self.name";工作得非常好。这是我的代码:

fn main() {
let student1 = IOT_student {
name: String::from("Husayn Abbas"),
age: 13,
education: String::from("O Levels"),
};
let instructor1 = IOT_instructor {
name: String::from("Imran Ali"),
age: 25,
};
println!("{}", student1.ask_Questions());
println!("{}", instructor1.ask_Questions());
}
trait Questions {
fn ask_Questions(&self) -> String;
}
struct IOT_student {
name: String,
age: i8,
education: String,
}
struct IOT_instructor {
name: String,
age: i8,
}
impl Questions for IOT_student {
fn ask_Questions(&self) -> String {
return format!("Zoom session will be LIVE, Zoom recording will not be available. Quarter 2 studio recorded videos are available on Portal.");
}
}
impl Questions for IOT_instructor {
fn ask_Questions(&self) -> String {
return format!("{} In case of any issue email to education@piaic.org", student1::name);
}
}

这是我的输出:

Compiling IOT_Assignment_2 v0.1.0 (/home/memelord/Documents/PIAIC Quarter 2 IOT Assignments/IOT_Assignment_2)
error[E0425]: cannot find value `student1` in this scope
--> src/main.rs:40:80
|
40 |         return format!("{} In case of any issue email to education@piaic.org", student1.name);
|                                                                                ^^^^^^^^ not found in this scope
warning: type `IOT_student` should have an upper camel case name
--> src/main.rs:21:8
|
21 | struct IOT_student {
|        ^^^^^^^^^^^ help: convert the identifier to upper camel case: `IotStudent`
|
= note: `#[warn(non_camel_case_types)]` on by default
warning: type `IOT_instructor` should have an upper camel case name
--> src/main.rs:27:8
|
27 | struct IOT_instructor {
|        ^^^^^^^^^^^^^^ help: convert the identifier to upper camel case: `IotInstructor`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0425`.
error: could not compile `IOT_Assignment_2`.
To learn more, run the command again with --verbose.

你知道为什么会发生这种情况吗(我是Rust初学者,所以请尽量简化你的解释(?

特性实现方法与调用它们的函数在完全不同的领域中。

如果你想在调用中使用学生的名字,你必须在函数中添加一个参数。示例:

impl Questions for IOT_instructor {
fn ask_Questions(&self, student: &IOT_student) -> String {
return format!("{} In case of any issue email to education@piaic.org", student.name);
}
}

现在调用类似:

println!("{}", instructor1.ask_Questions(&student1));

最新更新