【发布时间】:2018-09-10 04:10:05
【问题描述】:
我正在编写一个方法来循环遍历地图的(from, to) 并执行多轮tmp = tmp.replace(from, to)。我仍在尝试掌握 Rust 的所有权概念
#[macro_use]
extern crate lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref REPLACEMENTS: HashMap<&'static str, &'static str> = {
let mut m = HashMap::new();
m.insert("abc", "def");
m.insert("com", "org");
m
};
}
fn replace_path_name(path: &str) -> &str {
let mut tmp = path;
for (from, to) in REPLACEMENTS.iter() {
let a = *from;
let b = *to;
tmp = tmp.replace(a, b);
}
tmp
}
fn main() {}
这段代码让我...
error[E0308]: mismatched types
--> src/main.rs:22:15
|
22 | tmp = tmp.replace(a, b);
| ^^^^^^^^^^^^^^^^^
| |
| expected &str, found struct `std::string::String`
| help: consider borrowing here: `&tmp.replace(a, b)`
|
= note: expected type `&str`
found type `std::string::String`
额外的a 和b 是我试图弄明白为什么Rust 将from 和to 变成&&str。
【问题讨论】:
标签: string replace rust ownership