4 ms·
I read this post and I think I understand it, but I'm not really sure, so, a question: is there a way to unsafely accomplish compiling the early example by conj
by thenewwazoo 4y ago
I read this post and I think I understand it, but I'm not really sure, so, a question: is there a way to unsafely accomplish compiling the early example by conjuring lifetimes from the aether? Put another way, does the line that fails to compile fail because of some aspect of the concrete lifetime of the values involved, or is it truly an expressiveness problem that doesn't affect the simple type case (i64) because it's Copy (and thus has no lifetime)?
- armchairhacker 4y agoYes, you can use raw pointers. Example at https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a3f708558d92e33f20c5ca558dbe8705 https://play.rust-lang.org/?version=stable&mode=debug&editio.... The gist is trait TryConvertValue: Sized { /// SAFETY: `value` must be dereferencable. unsafe fn try_convert_value(value: *const Value) -> Option<Self>; } Now `TryConvertValue` has no lifetime so you don't get the HRTB issues presented in the rest of the article. The unsafeness is that if you call `try_convert_value(null())` or with a dead raw pointer you will cause UB. One issue with raw pointers though is that they don't extend to lifetime-generic types: there's no raw-pointer equivalent for #[derive(Debug)] enum Value<'a> { String(&'a str), Number(&'a i64), } trait TryConvertValue<'a>: Sized { fn try_convert_value(value: Value<'a>) -> Option<Self>; } I wish there was a feature where you could use raw pointers in generic argument position, like `Value<>` which would have variants `String(const str)`, `Number(*const i64)`, but I haven't heard anyone else suggest or advocate for it (`Value<'static>` is not the same)