[英]How can I set string values in a static mut array/vec?
I have a symbol table that I want to be static because it is accessed in a lot of circumstances where I don't have a good way to pass the value in. It is a struct and a table that looks like:我有一个我想成为 static 的符号表,因为它在很多情况下都可以访问,而我没有很好的方法来传递值。它是一个结构和一个看起来像的表:
struct Symbol {
string: &'static str,
other_values: ...,
}
const NO_SYMBOL = Symbol{ string: "", other...};
static mut symbol_table : [Symbol;100] = [NO_SYMBOL;100];
How do I update the string field?如何更新字符串字段? It has to be static, because it's in a static array, but I want to generate values (among other things, by reading from a file), so how can I make a String static so I can store it in an element of the array?它必须是 static,因为它在 static 数组中,但我想生成值(除其他外,通过从文件中读取),所以我怎样才能在数组中创建字符串 ZA81259CEF8E959C624ZD1D45E ?
There are a couple of ways to do this, depending on what you think is best.有几种方法可以做到这一点,具体取决于您认为最好的方法。 Use a Vec
:使用Vec
:
static mut symbol_table_1:Vec<Symbol> = Vec:new(); //doesn't actually allocate so is a const fn
or use an option and replace
the none values:或使用选项并replace
none 值:
static mut symbol_table_2:[Option<Symbol>;100] = [None;100];
unsafe{
symbol_table_2[0].replace(Some(value));
}
A &'static str
can be obtained by using String::into_boxed_str
and Box::leak
. &'static str
可以通过使用String::into_boxed_str
和Box::leak
获得。 However, I would highly encourage you to use lazy_static
and an RwLock
, which enables many readers or one writer to maintain a lock on the static
and prevent data races.但是,我强烈建议您使用lazy_static
和RwLock
,这使得许多读取器或一个写入器能够保持对static
的锁定并防止数据竞争。
lazy_static!{
static ref symbol_table_3:Rwlock<Vec<Symbol>> = RwLock::new(Vec::new());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.