Attempting to declare String const results in the expected type found "my string"

I am trying to declare a constant String

in Rust but I am getting a compiler error, I just cannot figure it out

const DATABASE : String::from("/var/lib/tracker/tracker.json");

      

and this is 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

      

+3


source to share


1 answer


You should read The Rust Programming Language, Second Edition , in particular the chapter that discusses constants . Correct declaration syntax const

:

const NAME: Type = value;

      

In this case:

const DATABASE: String = String::from("/var/lib/tracker/tracker.json");

      



However , this will not work because line allocation is not something that can be calculated at compile time. What it means const

. You can use a string snippet , specifically one with a static lifetime that is implied in const

and static

s:

const DATABASE: &str = "/var/lib/tracker/tracker.json";

      

Functions that just need to be read in a string must accept &str

, so this is unlikely to cause any problems. It also has the good advantage of not requiring any allocation, so it is quite effective.

If you need String

it, you probably have to mutate it. In this case, global policy will lead to threading problems. Instead, you should simply highlight when you need it with String::from(DATABASE)

and pass to String

.

+10


source







All Articles