In general it's suggested to accept &str instead of String in Rust.
Let's assume i have a couple of functions and a String instance:
use std::collections::HashMap;
fn do_something_str(string: &str) {
let mut map = HashMap::new();
map.insert(string.to_owned() /* copying (expensive)? */, "value");
}
fn do_something_string(string: String) {
let mut map = HashMap::new();
map.insert(string /* moving (cheap)? */, "value");
}
fn main() {
let string = String::from("123");
do_something_str(&string);
do_something_string(string);
}
Does copying happen in do_something_str() meaning it will be slower/higher temporary memory consumption?
PS. i know i don't have to call .to_owned() explicitly and the following will also work:
fn do_something_str(string: &str) {
let mut map = HashMap::new();
map.insert(string /* copying (expensive)? */, "value");
}
But since a hashmap owns keys i believe it will clone it implicitly. Please correct me, if i'm wrong.