How do I declare a “static” field in a struct in R

2019-06-15 00:31发布

How do I declare a "static" field in a struct in Rust, preferably with a default value:

struct MyStruct {
    x: i32,               // instance
    y: i32,               // instance
    my_static: i32 = 123, // static, how?
}

fn main() {
    let a = get_value();
    if a == MyStruct::my_static {
        //...
    } else {
        //...
    }
}

标签: rust
3条回答
何必那么认真
2楼-- · 2019-06-15 01:06

You can declare an associated constant in an impl:

struct MyStruct {
    x: i32,
    y: i32,
}

impl MyStruct {
    const MY_STATIC: i32 = 123;
}

fn main() {
    println!("MyStruct::MY_STATIC = {}", MyStruct::MY_STATIC);
}
查看更多
太酷不给撩
3楼-- · 2019-06-15 01:10

Rust does not support static fields in structures, so you can't do that. The closest thing you can get is an associated method:

struct MyStruct {
    x: i32,
    y: i32,
}

impl MyStruct {
    #[inline]
    pub fn my_static() -> i32 {
        123
    }
}

fn main() {
    let a = get_value();
    if a == MyStruct::my_static() {
        //...
    } else {
        //...    
    }
}
查看更多
成全新的幸福
4楼-- · 2019-06-15 01:12

You can't declare a field static in a struct.

You can declare a static variable at module scope like this :

static FOO: int = 42;

And you can't have a static variable mutable without unsafe code : to follow borrowing rules it would have to be wrapped in a container making runtime borrowing checks and being Sync, like Mutex or RWLock, but these cannot be stored in static variable as they have non-trivial constructors.

查看更多
登录 后发表回答