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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I know, but the function is a library, can't change it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.