我正在尝试定义静态非可变数据,在AVR的闪存中使用它们(因此是静态的),但我坚持这种情况(这是一个简历)。
trait MenuOption {
fn get_title(&self) -> String;
}
struct Op<'a> {
title: &'a str,
}
impl MenuOption for Op<'static> {
fn get_title(&self) -> String {
self.title.to_string()
}
}
struct Menu<'a> {
options: &'a [&'a MenuOption],
}
static MAIN_MENU: Menu = Menu {
options: &[&Op { title: "Op1" }],
};
fn main() {}
这段代码给了我这个错误:
error[E0277]: the trait bound `MenuOption + 'static: std::marker::Sync` is not satisfied in `Menu<'static>`
--> src/main.rs:19:1
|
19 | / static MAIN_MENU: Menu = Menu {
20 | | options: &[&Op { title: "Op1" }],
21 | | };
| |__^ `MenuOption + 'static` cannot be shared between threads safely
|
= help: within `Menu<'static>`, the trait `std::marker::Sync` is not implemented for `MenuOption + 'static`
= note: required because it appears within the type `&'static MenuOption + 'static`
= note: required because it appears within the type `[&'static MenuOption + 'static]`
= note: required because it appears within the type `&'static [&'static MenuOption + 'static]`
= note: required because it appears within the type `Menu<'static>`
= note: shared static variables must have a type that implements `Sync`
我可以将MAIN_MENU
声明为const
而不是static
,或将Menu::options
定义为&'a [&'a Op<'a>]
使用结构Op
我想使用约束MenuOption
。
此时我有点困惑。什么是共享非可变数据的问题?这可能与数据不可变但与使用约束有关。
这可以在不MAIN_MENU
const
的情况下完成吗?可以使用const
吗?我知道这不会有固定的分配,而是编译器会根据需要注入数据。