gpt4 book ai didi

rust - 如何让函数返回拥有字符串的 HashMap ?

转载 作者:行者123 更新时间:2023-12-02 16:10:53 24 4
gpt4 key购买 nike

use std::collections::BTreeMap;

#[derive(Debug)]
struct TestStruct {
name: String,
num: f64,
}

fn main() {
let test_struct = TestStruct {name: "Test".to_string(), num: 0.42 };
println!("{:?}", test_struct);
}


fn get_fields_as_map(test_struct: &TestStruct) -> BTreeMap<&str, &str> {
let mut field_map: BTreeMap<&str, &str> = BTreeMap::new();
field_map.insert("name", &test_struct.name);
field_map.insert("num", &test_struct.num.to_string());
field_map
}

playground

这会产生错误:

error[E0515]: cannot return value referencing temporary value
--> src/main.rs:19:5
|
18 | field_map.insert("num", &test_struct.num.to_string());
| --------------------------- temporary value created here
19 | field_map
| ^^^^^^^^^ returns a value referencing data owned by the current function

我认为这是有道理的。 to_string() 函数正在分配一个字符串,该字符串的生命周期就是该函数的生命周期。我还没有弄清楚如何分配字符串,使其具有与 BTreeMap 相同的生命周期。我尝试了几种不同的方法但都没有成功,觉得我错过了什么。我不完全了解所有权。

最佳答案

如果让映射拥有其中的字符串而不是存储引用,就可以避免头痛。引用意味着涉及生命周期,正如您所发现的那样,很难构造具有所需生命周期的 &str

&str 引用更改为拥有的 String ,生活很简单:

fn get_fields_as_map(test_struct: &TestStruct) ->  BTreeMap<String, String> {
let mut field_map = BTreeMap::new();
field_map.insert("name".to_owned(), test_struct.name.to_owned());
field_map.insert("num".to_owned(), test_struct.num.to_string());
field_map
}

关于rust - 如何让函数返回拥有字符串的 HashMap ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68052670/

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