3

In a library I'm writing to understand Rust I created a trait Decodeable.

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

I then implemented the type:

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

This was failing with an error of:

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

I eventually figured out if I change the function signature to read_and_decode(stream: &mut types::ReadSeeker), it worked.

I'd like to understand what the difference between &mut stream: types::ReadSeeker and stream: &mut types::ReadSeeker. This feels like it is a fundamental part of rust, but I don't have any grasp on what the difference is beyond the fact that they are in fact different.

Tabitha
  • 2,554
  • 1
  • 21
  • 21

1 Answers1

2

&mut x: T is not valid, unless T is a &mut U.

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

gives this error:

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

However, the following function is valid:

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

What &mut x: &mut U means is, given a value of type &mut U, destructure the &mut U by dereferencing it and assign the result to x (this is only valid if U implements Copy, otherwise you'll get a "cannot move out of borrowed content" error). In this situation, &mut x is a pattern. You also find patterns in let statements and in match arms, and the meaning is always the same.

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

In practice, we rarely write something like &mut a: &mut T in a function signature.

Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
  • Thanks this helped. I happened to also find [28587698](http://stackoverflow.com/questions/28587698/whats-the-difference-in-mut-before-a-variable-name-and-after-the?rq=1) which this is a duplicate of so I'm going to close the question. – Tabitha Feb 11 '16 at 22:37