Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to declare a String const results in expected type, found "my 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
like image 418
arsalan86 Avatar asked Jul 18 '17 20:07

arsalan86


People also ask

How do you declare a string const?

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.

Can a string be const?

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.

What is a static string in Rust?

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.


1 Answers

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 consts and statics:

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:

  • How to create a static string at compile time
like image 109
Shepmaster Avatar answered Oct 16 '22 19:10

Shepmaster