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

Ashish Myles marcianx at gmail.com
Wed Jan 8 20:43:42 PST 2014


That'll do it, thanks! :)

Here's to hoping that the compiler is smart enough to remove the
bounds-checks and the None pathway for when I is one of the unsigned
integer primitives.

Ashish


On Wed, Jan 8, 2014 at 11:21 PM, Brendan Zabarauskas <bjzaba at yahoo.com.au>wrote:

> 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
>
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140108/ab304b32/attachment.html>


More information about the Rust-dev mailing list