我有一个大致看起来像这个简化例子的枚举:
use std::collections::BTreeMap;
enum Value {
Null,
Object(BTreeMap<String, Value>)
}
现在,我希望根据字段名称列表深入查看Value::Object
并使用给定字段对其进行初始化。叶子字段应始终接收Value::Null
变体。
我希望以及以前做过的事情如下:
fn set_null_to_how_i_want_it(fields: &[&str], mut v: &mut Value) {
debug_assert!(fields.len() > 0);
for (fid, field) in fields.iter().enumerate() {
v =
match *v {
Value::Object(ref mut map) => {
let val_to_insert =
if fid == fields.len() - 1 {
Value::Null
} else {
Value::Object(Default::default())
};
map.entry(field.to_string()).or_insert(val_to_insert)
}
_ => unreachable!(),
}
}
}
但是,借阅检查员不会允许它。
有趣的是,有效的是以下,更复杂,可能性能更差的实施:
fn set_null_how_borrow_chk_allows_it(fields: &[&str], v: &mut Value) {
let next =
match *v {
Value::Object(ref mut map) => {
let val_to_insert =
if fields.len() == 1 {
Value::Null
} else {
Value::Object(Default::default())
};
map.entry(fields[0].to_string()).or_insert(val_to_insert)
},
_ => unreachable!()
};
if fields.len() > 1 {
set_null_how_borrow_chk_allows_it(&fields[1..], next)
}
}
使用上面的版本,以下所有代码都运行良好:
let mut v = Value::Object(Default::default());
let fields = ["foo", "bar", "baz"];
set_null_how_borrow_chk_allows_it(&fields, &mut v);
let mut map_count = 0;
for (fid, field) in fields.iter().enumerate() {
let next =
match v {
Value::Object(mut map) => {
map_count += 1;
map.remove(&field.to_string()).unwrap()
},
_ => unreachable!()
};
v = next;
}
assert_eq!(map_count, fields.len());
match v {
Value::Null => (),
Value::Object(_) => unreachable!(),
}
有没有更好的方法来初始化嵌套枚举或让set_null_to_how_i_want_it(...)
工作?
您可以查看完整的示例on github,并按照以下方式使用它:
git clone https://github.com/Byron/depot
cd depot/src/rust/hello
cargo test --test lang
# edit src/rust/hello/tests/lang.rs for testing
➜ hello git:(master) ✗ rustc --version --verbose
rustc 1.1.0-nightly (4b88e8f63 2015-05-11) (built 2015-05-12)
binary: rustc
commit-hash: 4b88e8f63eeaf557c916a0a1e73150b028c44c52
commit-date: 2015-05-11
build-date: 2015-05-12
host: x86_64-apple-darwin
release: 1.1.0-nightly
答案 0 :(得分:1)
The borrow checker works on names, and so some examples like your first approach don’t work; this can be worked around by moving the value Application
to a different name first and then assigning the new value to v
:
v