我想有一个静态的Uuid在我的锈蚀程序,但我不知道如何做它。
我试过了,但不起作用
fn type_id() -> &'static uuid::Uuid {
let tmp = "9cb4cf49-5c3d-4647-83b0-8f3515da7be1".as_bytes();
let tmp = uuid::Uuid::from_slice(tmp).unwrap();
&tmp
}
error: cannot return reference to local variable `tmp`
returns a reference to data owned by the current function (rustc E0515)发布于 2022-02-04 14:56:42
假设您使用的是the uuid crate,一些“构造函数”函数是const。因此,您只需调用它们“通常”来初始化您的静态(这是一个const上下文)。
遗憾的是,操场上没有uuid,但我想出了如下几点:
static TYPE_ID: Uuid = Uuid::from_u128(0x9cb4cf49_5c3d_4647_83b0_8f3515da7be1);或者使用hex_literal机箱,如果您更喜欢字符串外观:
static TYPE_ID: Uuid = Uuid::from_bytes(hex!("9cb4cf49 5c3d 4647 83b0 8f3515da7be1"));发布于 2022-02-04 14:47:45
谢谢@PitaJ。使用once_cell:Lazy是可行的。我仍然想知道是否有一种更简单的方法来做这件事,所以我不会将答案标记为已被接受。
static TYPE_ID: Lazy<uuid::Uuid> = Lazy::new(|| {
let tmp = "9cb4cf49-5c3d-4647-83b0-8f3515da7be1";
let tmp = uuid::Uuid::from_str(tmp).unwrap();
tmp
});https://stackoverflow.com/questions/70988130
复制相似问题