如何在没有赋值的情况下声明静态可变变量?

mak*_*aki 7 static global declaration rust

我尝试了以下内容

struct mbuf
{
  cacheline: *mut [u64],               // great amount of rows follows below
  // ..........
}
static mut arr: [mbuf; 32];                // Q1 my main aim
// something as before but using Vec;      // Q2 also main aim

fn main() {
 // let static mut arr: [mbuf; 32];        // Q3 also doesn't work
 // static mut arr: [mbuf; 32];            // Q3 also doesn't work
}
Run Code Online (Sandbox Code Playgroud)

并得到错误

src/main.rs:74:29: 74:30 error: expected one of `+` or `=`, found `;`
src/main.rs:74   static mut arr: [mbuf; 32];
                                           ^
Run Code Online (Sandbox Code Playgroud)

Q1,Q2,Q3 - 是否可能以及如何?

Chr*_*gan 8

声明时必须分配静态或常量; 在那之后他们永远不会被分配.

静态必须纯粹是文字; 它不能有任何函数调用.

目前,常量必须是纯粹的文字,但是当RFC 911,const fn被实现时,可以更像你想要的东西.

在函数里,你可以有staticconst项目,只是作为一个功能之外,并没有什么区别,放置物品(特征和类型定义,功能,&C. )的内部函数纯粹从外面范围隐藏它们.因此,您通常也可以使用let foo.


Art*_*mGr 6

您可以使用lazy-static在第一次访问时初始化静态数组,即使它可能会产生最小的开销(每次访问静态变量时它似乎都会调用Once :: call_once).

例如,Cargo.toml:

[package]
name = "arr"
version = "0.0.1"

[[bin]]
name = "arr"
path = "arr.rs"

[dependencies]
lazy_static = "*"
Run Code Online (Sandbox Code Playgroud)

arr.rs:

#[macro_use]
extern crate lazy_static;
use std::mem;
use std::ptr;

#[derive(Debug)]
struct Mbuf {
    cacheline: *mut u64,
}
// Let's pretend it's thread-safe to appease the lazy_static! constrains.
unsafe impl Sync for Mbuf { }

lazy_static! {
    static ref ARR: [Mbuf; 32] = {
        let mut tmp: [Mbuf; 32] = unsafe { mem::uninitialized() };
        for idx in 0..tmp.len() {
            tmp[idx] = Mbuf { cacheline: ptr::null_mut() };
        }
        tmp
    };
}

fn main() {
    println!("{:?}", *ARR);
}
Run Code Online (Sandbox Code Playgroud)

或者,只需创建自己的懒惰访问器:

use std::mem;
use std::ptr;

#[derive(Debug)]
struct Mbuf {
    cacheline: *mut u64,
}

static mut ARR: Option<[Mbuf; 32]> = None;
fn arr() -> &'static mut [Mbuf; 32] {
    unsafe {
        if ARR.is_none() {
            let mut tmp: [Mbuf; 32] = mem::uninitialized();
            for idx in 0..tmp.len() {
                tmp[idx] = Mbuf { cacheline: ptr::null_mut() };
            }
            ARR = Some(tmp);
        }
        mem::transmute(ARR.as_mut().unwrap())
    }
}

fn main() {
    println!("{:?}", arr());
}
Run Code Online (Sandbox Code Playgroud)

不用说,这段代码不是线程安全的,因此避免了一些Rust安全保证,但对于速度比较端口来说就足够了.