Hey all,
New to Rust; first post here.
I'm trying to find how I should approach the following scenario:
- Reading a text file line by line.
- If I find token
first_name=John
, save "John" for later. - If I find token
last_name=Doe
, printfirst_name
andlast_name
, i.e. "John Doe".
(One of) The "gotchas" is:
- In a malformed input file, I might hit
last_name
beforefirst_name
.
I know that this code is awful in many ways, but the concept I'm trying to get my head around is declaring variables that will get populated later, but might not (because of malformed input).
Specifically, my questions are:
- At
??? 1 ???
, how do/should I declare, but not initialize the variable? - Am I thinking about this all wrong?
I currently have this:
// Read the file, line by line
let reader = BufReader::new(file);
let mut first_name... // ??? 1 ???, in python: first_name = None
for line in reader.lines() {
let line = match line {
Ok(line) => line,
Err(error) => {
println!("Error reading line from file: {:?}", error);
process::exit(1);
}
};
if line.contains("first_name") {
println!("found first_name: {}", line);
first_name = line.replace("first_name=", "");
}
if line.contains("last_name") {
println!("found last_name: {}", line);
let last_name = line.replace("last_name=", "");
if first_name... // python: is not none:
println!("name: {} {}", first_name, last_name);
}
}
It doesn't feel right, because I suspect Rust will demand I am more safe than this, but I can't think how to be.
Any pointers greatly appreciated!
Thanks!