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
To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.
7 months ago. by John Otieno. A static variable refers to a type of variable that has a fixed memory location. They are similar to constant variables except they represent a memory location in the program.
You should read The Rust Programming Language, specifically the chapter that discusses constants. The proper syntax for declaring a const
is:
const NAME: Type = value;
In this case:
const DATABASE: String = String::from("/var/lib/tracker/tracker.json");
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";
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.
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
.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With