Skip to content

Box<Any> does not fulfil 'static. #15423

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
smosher opened this issue Jul 4, 2014 · 1 comment
Closed

Box<Any> does not fulfil 'static. #15423

smosher opened this issue Jul 4, 2014 · 1 comment

Comments

@smosher
Copy link

smosher commented Jul 4, 2014

$ ⮀rustc --version
rustc 0.11.0-pre-nightly (4c39962 2014-06-22 00:01:34 +0000)
host: x86_64-unknown-linux-gnu

Test case:

use std::any::Any;
use std::any::AnyRefExt;

struct Object { val: Box<Any> }

impl Object {
    fn new_int() -> Object { Object { val: box 5 as Box<Any> } }
    fn new_vec() -> Object {
        let mut v: Vec<Object> = vec!();
        v.push( Object::new_int() );
        Object { val: box v as Box<Any> }
    }
}

fn main() {
    let t = Object::new_vec();
    let v = t.val.as_ref::<Vec<Object>>();
}

Produces the error:

golf.rs:17:10: 17:39 error: instantiating a type parameter with an incompatible type `collections::vec::Vec<Object>`, which does not fulfill `'static`
golf.rs:17      let v = t.val.as_ref::<Vec<Object>>();

(In general, any attempts to .as_ref::<T>() where T contains Box<Any> will fail.)

I find this confusing, since box v as Box<Any> on line 11 should produce more or less the same error. Yet if you compile this with line 17 commented out, there are no errors (there are warnings about dead code/unused variables.)

Issue #7268 looks similar, but I can't convince myself that these two are the same. Line 17 doesn't ask for anything line 11 doesn't provide.

@alexcrichton
Copy link
Member

Closing as working as intended. The as_ref function specifically takes <T: 'static> which means that the only invalid thing done here is the call to as_ref (not the construction).

What you need to do is to specify that Object adheres to a 'static lifetime via:

struct Object { val: Box<Any + 'static> }

That way rustc can understand that the boxed trait indeed doesn't have any borrowed pointers.

bors added a commit to rust-lang-ci/rust that referenced this issue Aug 21, 2023
…ct_to_tuple_struct, r=lnicola

internal : Deunwrap convert_named_struct_to_tuple_struct

Replaces `unwrap`s with `?` for the mentioned assist.
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants