我想在可变借入中替换一个值; 将其中的一部分移动到新值中:
enum Foo<T> {
Bar(T),
Baz(T),
}
impl<T> Foo<T> {
fn switch(&mut self) {
*self = match self {
&mut Foo::Bar(val) => Foo::Baz(val),
&mut Foo::Baz(val) => Foo::Bar(val),
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,并且可以理解的是,将值移出会self破坏它的完整性.但由于之后立即删除了该值,我(如果不是编译器)可以保证它的安全性.
有没有办法实现这个目标?我觉得这是一个不安全代码的工作,但我不确定这是如何工作的.
为了学习Rust,我正在实现一个AVL树/字典.为了插入一个新元素,我下到树中,直到找到一个可以插入它的节点.不幸的是,它抱怨了借用指针的几个问题,而且我在解密它们时遇到了麻烦.
我已经突出显示了哪里出现错误.
enum AVLTree<T, U> {
Tree(T, U, Box<AVLTree<T, U>>, Box<AVLTree<T, U>>),
Empty,
}
impl<T, U> AVLTree<T, U>
where T: PartialOrd + PartialEq + Copy,
U: Copy
{
fn insert_element(&mut self, key: T, val: U) {
let new_node = AVLTree::Tree(key, val, Box::new(AVLTree::Empty), Box::new(AVLTree::Empty));
if let AVLTree::Empty = *self {
*self = new_node;
return;
}
let mut at = self;
loop {
match at {
&mut AVLTree::Tree(key2, _, ref mut left, ref mut right) => {
// ^~~~~~~~~~~~
// error: cannot …Run Code Online (Sandbox Code Playgroud) 我正在用一个方法编写一个模块foo,它bar在接收者的类上调用一个类方法.我当前的方法是使用self.class.bar,除非在实例类中定义类方法而不是"真实"类方法,否则它的工作正常:
module M
def foo
self.class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => NoMethodError: undefined method `bar' for Object:Class
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为obj.class不返回单例类.我可以使用obj.singleton_class,一切都会顺利进行:
module M
def foo
self.singleton_class.bar
end
end
obj = Object.new
class << obj
include M
def self.bar
42
end
end
obj.foo # => 42
Run Code Online (Sandbox Code Playgroud)
只有在单例类上定义方法的原因与上述相同.更糟糕的是,它为每个接收器创建了一个新的单例类,我想避免这些类,因为这些可能是相当多的对象.所以相反,我想要一些方法来检索对象的单例类,当且仅当它已经被定义时,即类型的东西obj.has_singleton_class ? obj.singleton_class : obj.class.我找不到任何方法来执行此检查.