rust/tests/ui/cast/ptr-to-trait-obj-different-regions-lt-ext.rs
2024-07-04 17:56:09 +02:00

32 lines
709 B
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//@ check-fail
//
// issue: <https://github.com/rust-lang/rust/issues/120217>
#![feature(arbitrary_self_types)]
trait Static<'a> {
fn proof(self: *const Self, s: &'a str) -> &'static str;
}
fn bad_cast<'a>(x: *const dyn Static<'static>) -> *const dyn Static<'a> {
x as _ //~ error: lifetime may not live long enough
}
impl Static<'static> for () {
fn proof(self: *const Self, s: &'static str) -> &'static str {
s
}
}
fn extend_lifetime(s: &str) -> &'static str {
bad_cast(&()).proof(s)
}
fn main() {
let s = String::from("Hello World");
let slice = extend_lifetime(&s);
println!("Now it exists: {slice}");
drop(s);
println!("Now its gone: {slice}");
}