【发布时间】:2019-09-22 10:17:30
【问题描述】:
有没有办法在 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();
|
How to create a static string at compile time 不能解决我的问题,因为它是关于 &'static str,而不是 String。我需要String 可以全局寻址。
【问题讨论】:
-
考虑到它是
static,您可以将其设为静态字符串切片(&'static str),而不是分配给String的堆。另见stackoverflow.com/q/32956050/1233251 和stackoverflow.com/q/27791532/1233251 -
对于
static String是(或将会是)什么可能存在误解。static是全局可寻址的(也可以在任何地方看到,包括来自其他库的对象)。'static(注意')表示可以跨越整个程序生命周期的生命周期;任何static都有一个生命周期'static。根据定义,String是一个堆分配的结构,它拥有str,但也可以扩展大小(通过重新分配)。static String为此没有多大意义。您可能想要'static String,请参阅其他评论 -
作为对原始问题的评论,将此问题标记为单例模式的副本感觉很苛刻。两个答案相同的问题不是同一个问题。特别是在这种情况下,当涉及到字符串时,这些字符串是拥有的和可变的,并且具有与 &'static str 不同的处理方式。