rust - 如何让函数返回拥有字符串的哈希映射?
问题描述
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
}
这会产生错误:
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
具有所需生命周期的 s 。
更改&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
}
推荐阅读
- javascript - 从 API json 多个 url 获取数据到 html 表中
- python - 使用Python在同一火花数据框中的两行之间减去数据
- javascript - d3.js 中的路径转换不起作用
- javascript - 如何使用此 foreach 通过 id 调用图像
- bazel - Bazel toolchain_vanilla 和 java_toolchain 有什么区别?
- php - 用于原始 SQL 查询的等效 Laravel Eloquent
- reactjs - 如何使用 React Fusion Charts 修复漏斗图的 ChunkLoadError?
- r - R Shiny 中基于动态组的过滤 - 通过标签复制搜索
- memory-address - 如果您在哪里重新排列内存地址缓存位分配,有什么区别吗?
- accessibility - 使用占位符作为标签是否符合 WCAG 2?