Skip to content

How to extract static reference from Option? #28839

Closed
@Virtlink

Description

@Virtlink

I have a static Option<&'static mut Foo> and I want to get the reference out of it. I know this is unsafe, but I can't seem to be able to figure out how to do this. First I tried this:

pub trait Foo { }

static mut _foo: Option<&'static mut Foo> = None;

pub fn get_foo() -> &'static mut Foo {
    unsafe { match _foo {
            Some(x) => x,
            None => panic!(),
    } }
}

The types should match, but I understand I'm trying to move x, which gives me this error:

src/lib.rs:21:15: 21:19 error: cannot move out of static item [E0507]
src/lib.rs:21         match _foo {
                            ^~~~
src/lib.rs:22:18: 22:19 note: attempting to move value to here
src/lib.rs:22             Some(x) => x,
                               ^
src/lib.rs:22:18: 22:19 help: to prevent the move, use `ref x` or `ref mut x`
                        to capture value by reference

So then I tried to use ref mut x to get a mutable reference, followed by *x to get the object back, but that also doesn't work:

pub trait Foo { }

static mut _foo: Option<&'static mut Foo> = None;

pub fn get_foo() -> &'static mut Foo {
    unsafe { match _foo {
            Some(ref mut x) => *x,
            None => panic!(),
    } }
}
src/lib.rs:22:32: 22:34 error: cannot move out of borrowed content [E0507]
src/lib.rs:22             Some(ref mut x) => *x,
                                             ^~

Finally I tried to clone or copy the &'static mut Foo, which also failed.

How do I fix this?

I'm using Rust 1.5.0-nightly (6108e8c 2015-09-28).


P.S. While typing this post I figured I try it on the Rust Playground. It fails to compile on nightly, but succeeds on beta and stable? (I'm writing a kernel and need the nightly features.)

Metadata

Metadata

Assignees

Labels

P-highHigh priorityT-langRelevant to the language teamregression-from-stable-to-nightlyPerformance or correctness regression from stable to nightly.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions