Skip to content

Instantly share code, notes, and snippets.

@krdlab
Created September 26, 2022 12:16
Show Gist options
  • Save krdlab/9d3d0dc6b1dddca3e7aca0fe4cb980a0 to your computer and use it in GitHub Desktop.
Save krdlab/9d3d0dc6b1dddca3e7aca0fe4cb980a0 to your computer and use it in GitHub Desktop.
struct フィールドを &mut で返す実験
struct Element {
value: i32,
}
impl Element {
pub fn change_to(&mut self, val: i32) {
self.value = val;
}
pub fn run(&self) {
println!("done {}", self.value);
}
}
struct Container {
data: Vec<Element>,
}
impl Container {
pub fn new(size: usize) -> Self {
let data = (0..size).map(|i| Element { value: i as i32 }).collect();
Self { data }
}
pub fn get_data(&mut self, i: usize) -> Option<&mut Element> {
self.data.get_mut(i)
}
}
fn main() {
let mut c = Container::new(10);
let elem = c.get_data(1).unwrap();
elem.change_to(777);
elem.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment