12

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

3
  • 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. Commented Dec 26, 2018 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. Commented Dec 26, 2018 at 13:58
  • Even if you want an owned string (String type), it is better to take an Into<String> so that your API is more flexible. Commented Dec 26, 2018 at 14:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.