0

There is a ALPHABET for arithmetic, it's const and used in a lot of functions. I want make the ALPHABET global, static, and const. Some functions need the ALPHABET type as &String, but str.to_string() function will happen once memory copy. this function is called frequently, so it's not good.

The used function is a library, can't change it.

static ALPHABET: &str = "xxxxxxxxxxxxxxxxxxxxxxx";

fn some1(value: &String, alphabet: &String) -> String {
    xxxx
}

fn main() {
    some1("test", ALPHABET); // Can't build
    some1("test", &ALPHABET.to_string()); // OK, but will happend memory copy.
}

How use the ALPHABET without to_string() function?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sloong
  • 51
  • 6
  • 2
    See also why [it is discouraged for functions to accept `&String` or `&Vec<_>` parameters](https://stackoverflow.com/questions/40006219). A well designed function would not require that. – E_net4 Nov 25 '20 at 08:56

1 Answers1

2

It would be better if your function uses &str instead:

fn some1(value: &str, alphabet: &str) -> String {
    xxxx
}

Playground

Since this is in a library you cannot modify, you could use lazy_static to instantiate a static reference to the String:

use lazy_static::lazy_static; // 1.4.0

lazy_static! {
    static ref APLHABET: String = "xxxxxxxxxxxxxxxxxxxxxxx".to_string();
}

Playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Netwave
  • 40,134
  • 6
  • 50
  • 93