Skip to content
HN On Hacker News ↗

struct's lifetime requirements can be bypassed via covariant field assignment

▲ 751 points • 446 comments • by formerly_proven • 3w ago • HN discussion ↗

Pangram verdict · v3.3

We believe that this entire text is human-written.

0 %

AI likelihood · overall

Human
100% human-written 0% AI-generated
SEGMENTS · HUMAN 1 of 1
SEGMENTS · AI 0 of 1
WORD COUNT 123
PEAK AI % 0% · §1
Analyzed
Oct 13
backend: pangram/v3.3
Segments scanned
1 windows
avg 123 words each
Distribution
100 / 0%
human / AI fraction
Verdict
Human
Pangram v3.3

Article text · 123 words · 1 segments analyzed

Human AI-generated
§1 Human · 0%

In the following code: use std::sync::Mutex; static KEPT: Mutex<Vec<Box<dyn std::any::Any + Send>>> = Mutex::new(Vec::new()); struct Q<T: 'static + Send>(Option<T>); impl<T: 'static + Send> Drop for Q<T> { fn drop(&mut self) { if let Some(t) = self.0.take() { KEPT.lock().unwrap().push(Box::new(t)); } } } fn main() { { let l = String::from("hello world, this is long enough"); let mut q = Q(None); q.0 = Some(&l); } let _z = String::from("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); let k = KEPT.lock().unwrap(); println!("{}", k[0].downcast_ref::<&'static String>().unwrap()); } I expected to see this happen: program is not accepted Instead, this happened: program compiles and prints XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. With asan, the program will crash with a AddressSanitizer: stack-use-after-scope Meta Issue on current nightly, and stables at least down to 1.85.0 Godbolt with asan: https://rust.godbolt.org/z/83MvfbKde Godbolt without asan: https://rust.godbolt.org/z/GsGdqqMWe