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?
Fileis notCopyand will be moved. - Herohtar