rausch
rausch

Reputation: 3388

Access newtype in Rust

I'm using a newtype, wrapping an array of integers:

struct Foo([int, ..5]);

Since, apparently, I cannot simply do this:

let foo = Foo([1,2,3,4,5]);
let bar = foo[2];

How exacty do I access the wrapped array?

Upvotes: 2

Views: 1280

Answers (1)

DK.
DK.

Reputation: 59005

There are one-and-a-half (soon to be two) ways:

#![feature(tuple_indexing)]

struct Foo([int, ..5]);

fn main() {
    let foo = Foo([1,2,3,4,5]);
    let Foo([_, foo_1, ..]) = foo;
    let foo_3 = foo.0[3];

    println!("[_, {}, _, {}, _]", foo_1, foo_3);
}

Specifically, tuple_indexing is likely to be un-gated soon, so you won't need the feature attribute to use it.

Basically, Foo is a tuple struct; that is, it behaves more or less just like a tuple that happens to have a name.

Upvotes: 7

Related Questions