I am new with rust and trying to understanding struct code and its related function.
i have write a code for struct but build_user function is not working and giving error that parameters defined in function are not defined in this scope. please help to resolve the issue. code is mentioned below along with error
*Error
Compiling struct_new v0.1.0 (D:\my_projects\struct_new)
error[E0425]: cannot find value email in this scope
--> src\main.rs:26:16
|
26 | build_user(email, addr);
| ^^^^^ not found in this scope
error[E0425]: cannot find value addr in this scope
--> src\main.rs:26:23
|
26 | build_user(email, addr);
| ^^^^ not found in this scope
error: aborting due to 2 previous errors
For more information about this error, try rustc --explain E0425.
error: could not compile struct_new.
Please help to resolve the issue where i am doing mistake.
It's not clear what you expect your code to do. There's indeed no email or addr variable where you are calling build_user(). You can see this by formatting your code:
#[derive(Debug)]
struct User {
email: String,
addr: String,
active: bool,
sign_in_count: u8,
}
fn main() {
let user = User {
email: String::from("babarsaed@hotmail.com"),
addr: String::from("National Telecom Faisalabad"),
active: true,
sign_in_count: 2,
};
fn build_user(_email: String, _addr: String) -> User {
User {
email: "babarsaed@gmail.com".to_string(),
addr: "NTC MSU FSD".to_string(),
active: true,
sign_in_count: 1,
}
}
// Where would `email` and `addr` come from?
build_user(email, addr);
println!("detail of user: {:#?}", user);
}
Thanks for your response, these are function parameters which i defined as build_user function parameters.
fn build_user(_email: String, _addr: String) -> User {
these two function parameters i defined and when i called function build_user i pass these two parameters.
// Where would `email` and `addr` come from?
build_user(email, addr);
As a variable, or directly in the call - this doesn't really matter, but now they are referring to nothing. There's no entity called email inside main, as well as no entity called addr.
// #[derive(Debug)]
struct User {
email: String,
addr: String,
active: bool,
sign_in_count: u8,
}
fn main () {
let user = User {
email: String::from("babarsaed@hotmail.com"),
addr: String::from("National Telecom Faisalabad"),
active: true,
sign_in_count: 2,
};
let mail = String::from("Babarsaed@gmail.com");
let address = String::from("NTC Faisalabad");
fn build_user (mail: String, address: String) -> User {
User {
email: mail,
addr: address,
active: true,
sign_in_count: 1,
}
};
println!("Function User Detail: {:#?}",build_user(mail, address));
println!("detail of user: {:#?}", user);
}
issue resolved i declare two variables in main and pass these variable to build_user function and code is worknig.
please check it is it ok now as code is giving outpout.