gpt4 book ai didi

string - 连接字符串并将它们转换为 &str

转载 作者:行者123 更新时间:2023-11-29 08:34:52 25 4
gpt4 key购买 nike

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在这里不是一个选项。

最佳答案

如果您需要从函数返回&str,那您就不走运了,参见Return local String as a slice (&str) .

如果您只是需要将切片放入HashMap 并将其进一步向下传递,您需要将String 存储在某处并且用对 String 的引用填充 map :

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() {}

我们使用 &*String Derefstr ,然后进行另一个引用以结束在 &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() {}

关于string - 连接字符串并将它们转换为 &str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37952798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com