11

I am trying to declare a const String in stable Rust but it does not let me declare it:

const CONSTANT_VALUE: String = String::from("constant value");

fn main() {
    println!("{}", TARGET_PORT_KEY);     
}

It is saying that:

Calls in constants are limited to tuple structs and tuple variants

I do not want to declare my string as literal and call to_string() on literal all the time.

What is the correct way to declare a constant String value?

Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68
  • 5
    A `String` is a growable buffer. Its purpose is to be modifiable. Why would you pass around a `String` if it's meant to be constant? Remember that API should usually take a `&str` as argument, not a `String`. The right constant type **is** `&str`. – Denys Séguret Dec 26 '18 at 13:45
  • Oh, I see the point. The main reason why I was asking that the API was taking `String` parameters but it seems these parameters are immutable and constant as well so yes I can change them to `&str` as well. Thanks for clearing that out. – Akiner Alkan Dec 26 '18 at 13:58
  • Even if you want an owned string (`String` type), it is better to take an `Into` so that your API is more flexible. – Boiethios Dec 26 '18 at 14:02

0 Answers0