Hi Rémi,

The problem in your code was that you have to return a &mut reference.
Here's a version of your code that works:

```
struct Mat {
    data:[float, ..16]
}

impl Mat {
    pub fn new() -> Mat {
        Mat { data: [0.0, ..16] }
    }
    pub fn Get<'a>(&'a mut self, r:int, c:int) -> &'a mut float {
        &mut self.data[r+c*4]
    }
}

fn main() {
    let mut a = Mat::new();
    *a.Get(0, 0) = 5.0;
    println(fmt!("%?", a));
}
```

Note that besides taking an &mut reference, we have to tell the compiler
that the lifetime of that reference is the same as of the original object,
which is done by anotating both references with the same lifetime variable
('a in this code).

Cheers,
Philipp


On Sat, Jun 22, 2013 at 10:35 AM, Rémi Fontan <[email protected]> wrote:

> Hi,
>
> is there a way to write something as follow in rust?
>
> class matrix {
> ...
>     float&   Get(int r, int c)    { return this.data[r + c*4]; }
> }
>
> matrix m;
> m.Get(0, 1) = 42.;
>
>
> in trust, my struct matrix would have a method called Get, but what would
> it return?
>
> struct Mat {
>     data:[float, ..16]
> }
>
> impl Mat  {
>     pub fn Get(&mut self, r:int, c:int) -> &mut float {
>         &self.data[r+c*4]
>     }
> }
>
>
> I get error messages about lifetime or about mutability
>
> est.rs:107:8: 107:24 error: mismatched types: expected `&mut float` but
> found `&float` (values differ in mutability)
> test.rs:107         &self.data[r*4+c]
>                     ^~~~~~~~~~~~~~~~
>
>
> cheers,
>
> Remi
> --
> Rémi Fontan : [email protected]
> mobile: +64 21 855 351
> 93 Otaki Street, Miramar 6022
> Wellington, New Zealand
>
> _______________________________________________
> Rust-dev mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/rust-dev
>
>
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to