When creating a new instance of a struct can you reference a previously initialized field within the struct under construction?
Example code:
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
#[derive(Debug)]
pub struct Test {
file_handle: File,
rdr: BufReader<File>,
}
impl Test {
pub fn new(filepath: std::path::PathBuf) -> Self {
Self {
file_handle: File::open(&filepath)
.expect(format!("Unable to open file {:?}", filepath).as_str()),
rdr: BufReader::new(file_handle),
}
}
}
fn main() {
let x = Test::new(PathBuf::from("my file"));
println!("{:?}", x);
}
Error generated:
error[E0425]: cannot find value `file_handle` in this scope
--> src/lib.rs:16:33
|
16 | rdr: BufReader::new(file_handle),
| ^^^^^^^^^^^ a field by this name exists in `Self`
Is there a specific pattern for this sort of thing, or is it just a Rust "no-no" (antithetical to the ideas of Rust)? How would something like this 'normally' be handled in Rust?
Update
@Netwave and @Herohtar have pointed out problems in my 'non-Rustian' expectations. Thank you, those comments both make sense and answer another un-ask question I had.
Still if I change my struct to
pub struct Test {
a: String,
b: String,
}
and my impl to something simple like:
pub fn new(ana: String) -> Self {
Self {
a: ana,
b: a.clone(),
}
}
I'll get a very similar error. I'm assuming Rust does not want me to use a struct field before the 'Self' block has been terminated. It seems to me the compiler could determine that the field has been set, so I suspect there is a deeper reason to prevent this behavior. I'm still in the very early stages of grok'ing the tao of Rust so I'd like to understand this (or any :-)) behavior better.