gpt4 book ai didi

rust - 在Rust中使用引用和使用拥有值之间有区别吗?

转载 作者:行者123 更新时间:2023-12-03 11:36:19 24 4
gpt4 key购买 nike

我正在读Rust书。它解释说,创建函数时,需要确定函数是要获取其参数的所有权,还是将其用作可变或不可变的引用。
我尚不完全清楚的是,在该函数中使用拥有的值还是使用引用之间在语法上存在差异。
如果您引用带有方法的结构,则使用这些方法的语法是否与处理自有变量时的语法完全相同?在如何使用拥有的变量和如何使用对该变量的引用之间还有其他区别吗?
什么时候需要取消引用引用变量?当您尝试增加由对int的可变引用或类似的引用所指向的变量存储的值时,我仅看到过取消引用。似乎只有打算用新的东西完全替换变量的值时才需要取消引用它。例如,如果要在对结构的引用上运行方法,则无需取消引用,但是如果要将值替换为该结构的完全不同的实例,则需要取消引用。是对的吗?

最佳答案

If you have a reference to a struct with methods, is the syntax for using those methods exactly the same as it would be if you were dealing with an owned variable? Are there any other difference between how one would use an owned variable, and how one would use a reference to that variable?


是的,除非您有一个不可变的引用,否则,您只能调用带有不可变引用的方法;如果您有一个可变的引用,则可以调用带有可变或不可变的引用的方法;如果您拥有所有权,则可以调用任何方法,包括那些拥有所有权的人。例子:
struct Struct;

impl Struct {
fn takes_self_ref(&self) {}
fn takes_self_mut_ref(&mut self) {}
fn takes_self(self) {}
}

fn func_owned(mut s: Struct) {
s.takes_self_ref(); // compiles
s.takes_self_mut_ref(); // compiles
s.takes_self(); // compiles
}

fn func_mut_ref(s: &mut Struct) {
s.takes_self_ref(); // compiles
s.takes_self_mut_ref(); // compiles
s.takes_self(); // error
}

fn func_ref(s: &Struct) {
s.takes_self_ref(); // compiles
s.takes_self_mut_ref(); // error
s.takes_self(); // error
}

When do you need to dereference a reference variable?


引用运算符 *,但是编译器会在方法调用时自动取消引用,这就是为什么您很少在实践中看到Rust代码中使用的引用运算符的原因,因为很少明确需要它。

关于rust - 在Rust中使用引用和使用拥有值之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65777741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com