[rust-dev] static mut and owning pointers

Kevin Ballard kevin at sb.org
Tue Jan 28 12:12:23 PST 2014


Your code is moving the contents of Option<~MyStruct> into the match arm. It just so happens that this seems to be zeroing out the original pointer in memory, and that happens to be the same representation that None does for the type Option<~MyStruct> (since ~ pointers are non-nullable), so the act of moving the value just happens to be transforming it into a None.

Normally you couldn't do this, but mutable statics are weird (which is why you need the unsafe block to access it).

When you remove the ~, the lines end up printing the same because MyStruct is implicitly copyable, so your match arm is now copying instead of moving.

The correct fix here is to use `Some(ref data)` instead of `Some(data)`. This will take a reference to the data instead of moving it, and the static will remain unchanged.

-Kevin

On Jan 28, 2014, at 11:48 AM, Alexander Stavonin <a.stavonin at gmail.com> wrote:

> Hi all! I’m not sure is it an error or "static mut" variables misunderstanding from my side. The source:
> 
> struct MyStruct {
>     val: int
> }
> 
> static mut global_data: Option<~MyStruct> = None;
> 
> fn test_call() {
>     unsafe {
>         match global_data {
>             Some(data) => { println!("We have data {:?}", data);}
>             None => { println!("We don't have data");}
>         }
>     }
> }
> 
> fn main() {
> 
>     unsafe {
>         global_data = Some(~MyStruct{val: 42});
>     }
> 
>     test_call();
>     test_call();
> }
> 
> and output:
> 
> We have data ~MyStruct{val: 42}
> We don't have data
> 
> But if I’m changing global_data from Option<~MyStruct> to Option<MyStruct> output is changed also:
> 
> We have data ~MyStruct{val: 42}
> We have data ~MyStruct{val: 42}
> 
> Is it normal behaviour and owning pointers cannot be stored in global variables or an error?
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140128/d17a07c7/attachment.html>


More information about the Rust-dev mailing list