[rust-dev] What type to put for index when impl-ing Index?

Brendan Zabarauskas bjzaba at yahoo.com.au
Wed Jan 8 20:21:40 PST 2014


struct Foo([f64, ..3]);

impl<I: Int> Index<I, f64> for Foo {
    fn index(&self, index: &I) -> f64 {
        let index = index.to_uint().unwrap();
        match self {
            &Foo(ref v) => v[index].clone()
        }
    }
}

fn main() {
    let tmp : uint = 0;
    let foo = Foo([1.0, 2.0, 3.0]);
    println!("{:?}", foo[tmp]);
}

On 9 Jan 2014, at 2:08 pm, Ashish Myles <marcianx at gmail.com> wrote:

> The following implementation of Index for Foo works fine.
> 
> struct Foo([f64, ..3]);
> impl Index<uint, f64> for Foo {
>     fn index(&self, index: &uint) -> f64 {
>         match self {
>             &Foo(ref v) => v[*index].clone()
>         }
>     }
> }
> fn main() {
>     let tmp : uint = 0;
>     let foo = Foo([1.0, 2.0, 3.0]);
>     println!("{:?}", foo[tmp]);
> }
> 
> But if tmp is of type int, then I get an int-uint type mismatch failure. So I tried the following.
> 
> use std::num::Int;
> ...
> impl<Idx : Int> Index<Idx, f64> for Foo {
>     fn index(&self, index: &Idx) -> f64 {
>         match self {
>             &Foo(ref v) => v[*index].clone()
>         }
>     }
> }
> 
> But I get
>     error: mismatched types: expected integral type but found `Idx`
> with the error pointing at *index above.  What's the right way to go about implementing generic operator indexing?  Or does one always require conversion to uint (in the first case above) on the caller's side?
> 
> Ashish
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev



More information about the Rust-dev mailing list