Skip to content

Instantly share code, notes, and snippets.

@bluenote10
Last active June 19, 2020 12:49
Show Gist options
  • Save bluenote10/8921bcc0302b066ef5e39bc6e9a8b7e3 to your computer and use it in GitHub Desktop.
Save bluenote10/8921bcc0302b066ef5e39bc6e9a8b7e3 to your computer and use it in GitHub Desktop.
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8921bcc0302b066ef5e39bc6e9a8b7e3
#![allow(dead_code)]
use std::collections::HashMap;
struct Test {
offset: f64,
buffers: HashMap<i32, Vec<f64>>,
data: Vec<f64>,
}
fn test(_data: &mut [f64]) {}
impl Test {
fn helper(&self, x: f64) -> f64 {
x - self.offset
}
fn mutself(&mut self) {}
fn process(&mut self) {
// Mutable iterator, immutable self borrow => not working
/*
for (id, buffer) in self.buffers.iter_mut() {
buffer[0] = self.helper(buffer[0]);
}
*/
// Immutable iterator, mutable borrow of self.buffer => not working
/*
for id in self.buffers.keys() {
let buffer = self.buffers.get_mut(id);
}
*/
/*
for id in self.buffers.keys() {
self.mutself();
}
*/
/*
for x in self.data.iter() {
self.mutself();
}
*/
// Cloning the keys is an option, but with overhead
let ids: Vec<i32> = self.buffers.keys().map(|key| key.clone()).collect();
for id in &ids {
let _buffer = self.buffers.get_mut(id);
}
// Also note that is is fine to borrow OTHER fields, even mutably
// although self is mutably borrowed:
for (_id, _buffer) in self.buffers.iter_mut() {
test(&mut self.data);
}
// Pulling out the iterator does not help either.
// Still the entire "self" gets borrowed.
/*
let iter = self.buffers.iter_mut();
for (id, buffer) in iter {
buffer[0] = self.helper(buffer[0]);
test(&mut self.data);
}
*/
// Doesn't work, because borrow lasts until the print.
// Note that if there is no usage after self.helper
// it would work, because the borrow ends directly.
/*
let iter = self.buffers.iter_mut();
self.helper(1.0);
println!("{}", iter.count());
*/
// Similar problem with immutable iter, and mutable self borrow.
/*
let iter = self.buffers.iter();
self.mutself();
println!("{}", iter.count());
*/
// Attempt to mutably borrow only self.buffers does not work.
// The borrow always includes "self" and lasts until the last
// usage in scope...
/*
let buffers = &mut self.buffers;
for (id, buffer) in buffers.iter_mut() {
buffer[0] = self.helper(buffer[0]);
}
*/
}
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment