rust - 类型上的 `&mut` 和函数签名中的标识有什么区别?

标签 rust

<分区>

在一个库中,我正在编写以了解 Rust,我创建了一个特征 Decodeable。

pub trait Decodeable {
    fn read_and_decode(&mut types::ReadSeeker) -> Result<Self, ::error::Error>;
}

然后我实现了类型:

impl Decodeable for u32 {
    fn read_and_decode(&mut stream: types::ReadSeeker) -> Result<u32, error::Error> {
        try!(stream.big_edian_read_u32());
    }
}

这是失败的错误:

error: method `read_and_decode` has an incompatible type for trait:
 expected &-ptr,
    found trait types::ReadSeeker

我最终发现,如果我将函数签名更改为 read_and_decode(stream: &mut types::ReadSeeker),它会奏效。

我想了解 &mut stream: types::ReadSeekerstream: &mut types::ReadSeeker 之间的区别。这感觉像是使用rust 的一个基本部分,但除了它们实际上不同这一事实之外,我不知道有什么区别。

最佳答案

&mut x: T 无效,除非 T&mut U

fn foo(&mut a: i32) {
    unimplemented!()
}

给出这个错误:

<anon>:1:8: 1:14 error: mismatched types:
 expected `i32`,
    found `&mut _`
(expected i32,
    found &-ptr) [E0308]
<anon>:1 fn foo(&mut a: i32) {
                ^~~~~~

但是,下面的函数是有效的:

fn foo(&mut a: &mut i32) {
    unimplemented!()
}

&mut x: &mut U 的意思是,给定一个 &mut U 类型的值,通过取消引用来解构 &mut U它并将结果分配给 x(这仅在 U 实现 Copy 时有效,否则你会得到一个“cannot移出借用的内容”错误)。在这种情况下,&mut x 是一个 pattern .您还可以在 let 语句和 match arm 中找到模式,它们的含义始终相同。

fn foo(a: &mut i32) {
    let &mut b = a;
    match a {
        &mut c => unimplemented!()
    }
}

在实践中,我们很少在函数签名中写类似&mut a: &mut T的东西。

关于rust - 类型上的 `&mut` 和函数签名中的标识有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35351273/

相关文章:

Rust Diesel 更新连接表

types - 如何从 HashMap 创建条目的 Vec?

c - 为什么更新大型静态 float 组的程序在 Rust 中比在 C 中慢?

rust - 为什么在使用 Iterator::collect 时得到 "type annotations needed"?

rust - 自动将 &String 强制转换为 &str

rust - 为什么对数组的嵌套引用不会强制转换为切片?

generics - 为什么 Rust 不允许 "let v = Vec<i32>::new();"?

generics - 元组上 std::ops 的通用实现

rust - 将Rust&str转换为&'static&str

Rustc 仅在分配溢出的值时发出警告