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/li
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;
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: