Concat String并将它们转换为& str

时间:2016-06-21 19:15:44

标签: string rust concat

fn lyrics_more_bottles(song_template: &mut String, number: i32) {
    let mut template_partials = HashMap::new();
    let mut start_num = number.to_string();
    let mut remaining_num = (number - 1).to_string();

    template_partials.insert("start", start_num + " bottles");
    template_partials.insert("repeat", start_num + " bottles");
    template_partials.insert("remaining", remaining_num + " bottles");
    template_partials.insert("message", "Take one down and pass it around");

    resolve_template(song_template, template_partials);
}

我无法将这些连接的字符串转换为&str。我试着把它们放到括号中并拨打.as_str()。没有运气。

我需要HashMap<&str, &str>,因此这里不能选择String

1 个答案:

答案 0 :(得分:2)

如果您需要从该函数返回&str,那么您运气不好,请参阅Return local String as a slice (&str)

如果只是需要将切片放入HashMap并将其向下传递,则需要将String存储在某处并将地图填入地图中String s:

use std::collections::HashMap;

fn resolve_template(_: &mut String, _: HashMap<&str, &str>) {}

fn lyrics_more_bottles(song_template: &mut String, number: i32) {
    let mut start_num = number.to_string();
    let mut remaining_num = (number - 1).to_string();

    let start = start_num.clone() + " bottles";
    let repeat = start_num + " bottles";
    let remaining = remaining_num + " bottles";

    let mut template_partials = HashMap::new();

    template_partials.insert("start", &*start);
    template_partials.insert("repeat", &*repeat);
    template_partials.insert("remaining", &*remaining);
    template_partials.insert("message", "Take one down and pass it around");

    resolve_template(song_template, template_partials);
}

fn main() {}

我们将&*用于Deref Stringstr,然后再引用另一个引用,最后到达&str

请注意,在创建字符串后,必须移动let mut template_partials,否则当删除字符串时,映射可能包含对无效内存的引用。此外,start_num需要克隆,因为它使用了两次。

就个人而言,我只使用format!并使用相同的字符串两次,而不是克隆和修改它两次:

use std::collections::HashMap;

fn resolve_template(_: &mut String, _: HashMap<&str, &str>) {}

fn lyrics_more_bottles(song_template: &mut String, number: i32) {
    let start_and_repeat = format!("{} bottles", number);
    let remaining = format!("{} bottles", number - 1);

    let mut template_partials = HashMap::new();

    template_partials.insert("start", &*start_and_repeat);
    template_partials.insert("repeat", &*start_and_repeat);
    template_partials.insert("remaining", &*remaining);
    template_partials.insert("message", "Take one down and pass it around");

    resolve_template(song_template, template_partials);
}

fn main() {}