Skip to content

Instantly share code, notes, and snippets.

@goertzenator
Created June 23, 2016 21:26
Show Gist options
  • Select an option

  • Save goertzenator/d0d6687e90eef9d13b8904178bf9aaee to your computer and use it in GitHub Desktop.

Select an option

Save goertzenator/d0d6687e90eef9d13b8904178bf9aaee to your computer and use it in GitHub Desktop.
associated static attempt
trait Resource {
fn resource() -> &'static mut i32;
}
struct MyStruct;
fn main() {
*u8::resource() = 123;
*MyStruct::resource() = 456;
println!("{:?}", u8::resource());
println!("{:?}", MyStruct::resource());
}
// I want this blanket impl to work but output is...
// 456
// 456
impl<T> Resource for T {
fn resource() -> &'static mut i32 {
static mut static_storage: i32 = 0;
unsafe{ &mut static_storage }
}
}
// Discrete impls work, but then this is work for my lib users,
// and I get the orphan trait problem. Output..
// 123
// 456
// impl Resource for u8 {
// fn resource() -> &'static mut i32 {
// static mut static_storage: i32 = 0;
// unsafe{ &mut static_storage }
// }
// }
// impl Resource for MyStruct {
// fn resource() -> &'static mut i32 {
// static mut static_storage: i32 = 0;
// unsafe{ &mut static_storage }
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment