Created
January 19, 2023 10:14
-
-
Save maurges/8596ccc14c66cc691b0b4908f49c753b to your computer and use it in GitHub Desktop.
Static lifetime can demote to any other lifetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let builder = Builder::new(); | |
let mut num = 1337; | |
let builder = builder.set_kek(&mut num); | |
builder.run() | |
} | |
trait Bar { | |
fn foo(&self); | |
} | |
impl Bar for () { | |
fn foo(&self) { | |
eprintln!("unit") | |
} | |
} | |
impl Bar for i64 { | |
fn foo(&self) { | |
eprintln!("i64: {}", self) | |
} | |
} | |
struct Builder<'a> { | |
kek: &'a mut dyn Bar, | |
} | |
impl<'a> Builder<'a> { | |
fn new() -> Self { | |
/* | |
// for immutable unsafe is not needed: | |
static UNIT: () = (); | |
Self { | |
kek: &UNIT, | |
} | |
*/ | |
// Safety: safe because mutable () is the same as immutable () | |
unsafe { | |
static mut UNIT: () = (); | |
Self { | |
kek: &mut UNIT, | |
} | |
} | |
} | |
fn set_kek(mut self, kek: &'a mut dyn Bar) -> Self { | |
self.kek = kek; | |
self | |
} | |
fn run(self) { | |
self.kek.foo() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment