我的源文件包含给定日期的许多产品的文本 CSV 行。我想使用 Rust 整理这些文件,以便我最终得到许多新的 objective-c SV 文件,每个产品一个,每个包含仅特定于该产品的部分行。
我目前的解决方案是遍历源文件的行并使用 HashMap<String, String>
收集每个产品的行。我拆分每个源代码行并使用包含产品 ID 的元素作为键,以获得 Entry
(占用或空置)在我的HashMap
.如果它是空的,我用一个新的 String
初始化这个值这是预先分配给定容量的,因此我可以在之后有效地 append 到它。
// so far, so good (the first CSV item is the product ID)
let mystringval = productmap.entry(splitsource[0].to_owned()).or_insert(String::with_capacity(SOME_CAPACITY));
然后我想将同一源代码行的格式化元素 append 到此 Entry
.网上有很多例子,比如
https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.entry
如果HashMap
如何使这项工作值是一个整数:
// this works if you obtain an Entry from a HashMap containing int vals
*myval += 1;
我还没有想出如何将更多文本 append 到 Entry
我从我的 HashMap<String, String>
获得使用这种语法,我已尽最大努力在线研究示例。在 Rust 数据结构中操作非数字条目的例子少得惊人。
// using the Entry obtained from my first code snippet above
*mystringval.push_str(sourcePortion.as_str());
尝试编译它会产生以下错误:
error: type `()` cannot be dereferenced
--> coll.rs:102:17
|
102 | *mystringval.push_str(sourcePortion.as_str());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
如何 append 到 String
在Entry
里面值(value)?
最佳答案
*mystringval.push_str(sourcePortion.as_str());
被解析为 *(mystringval.push_str(sourcePortion.as_str()));
并且由于 String::push_str
返回 ()
,你会得到 () cannot be dereferenced
错误。
在取消引用周围使用括号解决了优先级问题:
(*mystringval).push_str(sourcePortion.as_str());
*myval += 1
起作用的原因是因为一元 *
的优先级高于 +=
,这意味着它被解析为
(*myval) += 1
由于 or_insert
返回 &mut V
,您不需要在调用它的方法之前取消引用它。以下也适用:
mystringval.push_str(sourcePortion.as_str());
关于string - 如何 append 到 Rust 哈希表中的字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877284/