尝试声明String const结果为预期的类型,找到“ my string”。 [英] Trying to declare a String const results in expected type, found "my string"
问题描述
我正在尝试在Rust中声明一个 String
常量,但出现编译器错误,我什至无法理解
I'm trying to declare a String
constant in Rust, but I get a compiler error I just can't make sense of
const DATABASE : String::from("/var/lib/tracker/tracker.json");
这是我尝试编译时得到的内容:
and here's what I get when I try to compile it:
error: expected type, found `"/var/lib/tracker/tracker.json"`
--> src/main.rs:19:31
|
19 | const DATABASE : String::from("/var/lib/tracker/tracker.json");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: expected one of `!`, `+`, `->`, `::`, or `=`, found `)`
--> src/main.rs:19:64
|
19 | const DATABASE : String::from("/var/lib/tracker/tracker.json");
| ^ expected one of `!`, `+`, `->`, `::`, or `=` here
推荐答案
您应该阅读 Rust编程语言,第二版,特别是讨论常量的章节。声明 const
的正确语法为:
You should read The Rust Programming Language, second edition, specifically the chapter that discusses constants. The proper syntax for declaring a const
is:
const NAME: Type = value;
在这种情况下:
const DATABASE: String = String::from("/var/lib/tracker/tracker.json");
但是,这是行不通的,因为分配字符串是不是在编译时就可以计算的东西。这就是 const
的意思。您可能要使用字符串slice ,特别是具有静态生存期的切片,它隐含在 const
s和 static
s中:
However, this won't work because allocating a string is not something that can be computed at compile time. That's what const
means. You may want to use a string slice, specifically one with a static lifetime, which is implicit in const
s and static
s:
const DATABASE: &str = "/var/lib/tracker/tracker.json";
仅需要读取字符串的函数应接受& str
,因此这不太可能引起任何问题。
Functions that just need to read a string should accept a &str
, so this is unlikely to cause any issues. It also has the nice benefit of requiring no allocation whatsoever, so it's pretty efficient.
如果您需要一个 String,它也具有不需要分配的好处。
,您可能需要对其进行突变。在这种情况下,将其设置为全局会导致线程问题。相反,您应该只在需要时使用 String :: from(DATABASE)
进行分配,并传入 String
。
If you need a String
, it's likely that you will need to mutate it. In that case, making it global would lead to threading issues. Instead, you should just allocate when you need it with String::from(DATABASE)
and pass in the String
.
另请参见:
- How to create a static string at compile time
这篇关于尝试声明String const结果为预期的类型,找到“ my string”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!