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

Ashish Myles marcianx at gmail.com
Wed Jan 8 19:08:02 PST 2014


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140108/a3ff41ad/attachment.html>


More information about the Rust-dev mailing list