有几次,我遇到了一种场景,即可变引用和不可变引用都需要访问器方法.
对于大约3行代码,复制逻辑不是问题,但是当逻辑变得更复杂时,复制粘贴大块代码是不好的.
我希望能够重复使用这两个代码.
Rust是否提供了比复制粘贴代码或使用unsafe
次强制转换更好的处理方法?
例如.:
impl MyStruct {
pub fn get_foo(&self) -> &Bar {
// ~20 lines of code
// --- snip ---
return bar;
}
pub fn get_foo_mut(&mut self) -> &mut Bar {
// ~20 lines of code
// (exactly matching previous code except `bar` is mutable)
// --- snip ---
return bar;
}
}
下面是一个代码库的更详细摘录,其中一个不可变返回参数被转换为mutable,以支持函数的不可变和可变版本.这使用了包装指针类型(ConstP
和MutP
表示不可变和可变引用),但函数的逻辑应该是明确的.
pub fn face_vert_share_loop<V, F>(f: F, v: V) -> LoopConstP
where V: Into<VertConstP>,
F: Into<FaceConstP>
{
into_expand!(f, v);
let l_first = f.l_first.as_const();
let mut l_iter = l_first;
loop {
if l_iter.v == v {
return l_iter;
}
l_iter = l_iter.next.as_const();
if l_iter == l_first {
break;
}
}
return null_const();
}
pub fn face_vert_share_loop_mut(f: FaceMutP, v: VertMutP) -> LoopMutP {
let l = face_vert_share_loop(f, v);
return unsafe {
// Evil! but what are the alternatives?
// Perform an unsafe `const` to `mut` cast :(
// While in general this should be avoided,
// its 'OK' in this case since input is also mutable.
l.as_mut()
};
}