Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
fritz
Jul 26, 2003

I'm having trouble with BufWriter living inside an option. I'm creating it as:
code:
// cli.outfile is an Option<String>
let fh: Option<File> = match cli.outfile {
    None => None,
    Some(s) => {
	let file : Result<File> = File::create(&s);
        match file {
		Err(_) => None.
		Ok(f) => Some(f)
        }
}
What I can't figure out is how to borrow in such a way that I can write to the thing inside 'fh' and not consume it.

Something like

code:
match &fh {
	None => None,
	Some(&f) => writeln!(f, "output");
}
but this consumes fh in a way I can't figure out how to avoid.

I've been trying a number of things but they're getting increasingly convoluted in a way that makes me think I'm fighting the languge.

Adbot
ADBOT LOVES YOU

fritz
Jul 26, 2003

gonadic io posted:

You want `match fs.as_mut()`. That and `as_ref` seem pretty unknown but are one of my most-used Option methods tbh

That worked! Thanks!

fritz
Jul 26, 2003

gonadic io posted:

Once your code is more settled you'll find that clippy will tell you that lots of your matches are equivalent to functions like `map` and `ok` and so on, make the code much easier to read. No worries when just messing around though.

Yeah I'm already a big fan of clippy, but I wasn't even able to get the thing to compile so it wasn't helping.

fritz
Jul 26, 2003

Had a failure of intuition today.

code:
struct Dummy {
   pub data : Vec<f64>
}

let mut data : Vec< (usize, Dummy) > = Vec::new();
let mut table : HashMap< usize, Dummy > = HashMap::new();
// data gets filled somewhere along the way
for (i,j) in data {

   table.entry(i)
   .and_modify(|v| *v = j)
   .or_insert(j)
}
rustc errors at the or_insert because j is already moved in the and_modify. I'm confused because I would have thought that it wasn't possible for both code paths to execute, i.e. if it goes thru .and_modify, it won't go thru .or_insert, and vice versa.

fritz
Jul 26, 2003

Thanks for the wisdom everybody, I think I get it now.

Adbot
ADBOT LOVES YOU

fritz
Jul 26, 2003

A "pointer" can be something that indexes into an array. You could have a data structure that contains a next_index and prev_index and update those as you iterate thru.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply