类型推断和借用与所有权转让 [英] Type inference and borrowing vs ownership transfer

查看:84
本文介绍了类型推断和借用与所有权转让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Rust,但遇到了一些令人困惑的行为.以下代码编译正常并按预期工作(编辑:添加了除测试函数以外的代码,以前省略):

I am learning Rust and I've run into some confusing behaviour. The following code compiles fine and works as expected (edit: added code other than test function, previously omitted):

struct Container<'a> {
    contents : &'a mut i32,
}

fn main() {
    let mut one = Container { contents: &mut 5 };
    test(&mut one);
    println!("Contents: {}",one.contents);
}

fn test<'a>(mut x : &'a mut Container) {
    *x.contents += 1;
    let y = x;
    *y.contents += 1;
    x = y;
    println!("{:?}",*x.contents)
}

现在在声明中

let y = x;

类型是推断出来的.因为 x&'a mut Container 类型,我认为这将是等效的:

the type is inferred. Because x is of type &'a mut Container, I thought that this would be equivalent:

let y: &'a mut Container = x;

但是当我这样做时,编译器会出现问题:

But when I do that, the compiler takes issue:

test_3.rs:25:5: 25:10 error: cannot assign to `x` because it is borrowed
test_3.rs:25     x = y;
                 ^~~~~
test_3.rs:23:33: 23:34 note: borrow of `x` occurs here
test_3.rs:23     let y: &'a mut Container = x;

x 如何在正确工作的示例中没有被借用?我通过从正确工作版本中省略行 x = y; 进行测试,编译器说:

How is x not borrowed by that point in the correctly working example? I tested by omitting the line x = y; from the correctly working version and the compiler said:

test_3.rs:24:13: 24:14 note: `x` moved here because it has type `&mut Container<'_>`, which is moved by default

因此,当我没有明确定义类型而是借用其他方式时,我正在采取行动.发生了什么,我如何在明确给出类型的同时获得与以前相同的行为,以及是什么导致在一种情况下移动行为但在另一种情况下借用?

So I'm getting a move when I don't explicitly define the type but a borrow otherwise. What is going on, how do I get the same behavior as before while explicitly giving the type, and what is causing move behavior in one case but borrow in the other?

用完整程序编辑

推荐答案

什么时候做

let y = x;

移动发生了.x 被清空,可以这么说,所有权转移到 y.

a move happens. x is emptied, so to speak, and ownership is transferred to y.

当你做任何一个

let y: &mut _ = x;
let y: &'a mut _ = x;

x 被重新借用以帮助匹配生命周期.这大致翻译为

x is reborrowed to aid matching the lifetimes. This roughly translates to

let y: &mut _ = &mut *x;
let y: &'a mut _ = &mut *x;

这使得 x 非空,持有别名可变借用.因此分配给它必须等待 y 被销毁.或者,您可以预先移动它

This leaves x non-empty, holding an aliased mutable borrow. Assigning to it thus must wait for y to be destroyed. Alternatively, you can pre-move it

let tmp = x;
let y: &'a mut _ = tmp;

我承认这是不明显的行为,很遗憾你不能在不借用整个值的情况下借用值的内容.

I'll admit it's nonobvious behaviour, and it's a shame that you can't borrow the contents of a value without borrowing the whole value.

这篇关于类型推断和借用与所有权转让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆