[英]Scoping Issues when referring value from Struct Instance in Rust
所以我有了這個程序,一切都按照我的意願工作。 唯一的問題是底部的“student1.name”。 我想用“student1.name”替換“self.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);
}
}
這是我的 output:
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 初學者,所以請盡量讓你的解釋簡單)?
特征實現方法與調用它們的 function 完全不同。
如果您希望能夠在調用中使用學生的姓名,則必須向 function 添加一個參數。 例子:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.