Skip to content

Instantly share code, notes, and snippets.

@fitzgen
Created February 9, 2015 04:05
Show Gist options
  • Save fitzgen/34bbecfa93a9b7a21500 to your computer and use it in GitHub Desktop.
Save fitzgen/34bbecfa93a9b7a21500 to your computer and use it in GitHub Desktop.
use std::{mem,ptr};
fn box_map_in_place<T, F>(boxed: Box<T>, f: F) -> Box<T> where F: FnOnce(T) -> T {
unsafe {
let p : *mut T = mem::transmute(boxed);
ptr::write(p, f(ptr::read(p)));
return mem::transmute(p);
}
}
fn main() {
let b = Box::new("foo".to_string());
let c = box_map_in_place(b, |s| s + "bar");
println!("{}", c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment