有没有办法在Rust中创建静态字符串?
我尝试了这个:
static somestring: String = String::new();
但我遇到了这个错误:
error: `std::string::String::new` is not yet stable as a const fn
--> src/main.rs:2:29
|
2 | static somestring: String = String::new();
|
如何在编译时创建静态字符串并不能解决我的问题,因为它涉及到的是&'static str
,而不是String
。我需要使String
全局可访问。
static
,你可以将其作为静态字符串切片 (&'static str
),而不是堆分配的String
。另请参见 https://dev59.com/3lwY5IYBdhLWcg3wJU54 和 https://dev59.com/4V4c5IYBdhLWcg3wjq7R。 - E net4static String
的理解存在误解。static
表示可以全局访问(即可以在任何地方看到,包括其他库中的对象)。'static
(请注意引号)表示寿命可以跨越整个程序的生命周期;任何static
都具有生命周期'static
。 根据定义,String
是一个堆分配的结构,它保存了str
但也可以通过重新分配来扩展大小。 因此,static String
没有太多意义。 您可能需要一个'static String
,请查看另一条评论。 - user2722968