Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the element at variable index of a tuple?

Tags:

rust

I'm writing a function to read vectors from stdin, and here is what I have so far:

fn read_vector() -> (i64, i64, i64) {
    let mut vec = (0, 0, 0);
    let mut value = String::new();

    for i in 0..3 {
        io::stdin().read_line(&mut value).expect("Failed to read line");
        vec.i = value.trim().parse().expect("Failed to read number!"); // error!
    }
}

However, the annotated line contains an error:

error: no field `i` on type `({integer}, {integer}, {integer})`
  --> src/main.rs:13:13
   |
13 |         vec.i = value.trim().parse().expect("Failed to read number!");
   |             ^

Reading the documentation entry doesn't reveal any get, or similar function.

So, is there any way to get the ith value of a tuple?

like image 839
Rakete1111 Avatar asked Apr 03 '17 05:04

Rakete1111


People also ask

Can you access a tuple by index?

Because each item in a Python tuple has a corresponding index number, we're able to access items. In addition to positive index numbers, we can also access items from the tuple with a negative index number, by counting backwards from the end of the tuple, starting at -1 .

How do you access a specific element in a tuple?

Accessing Elements in a Tuple We can access elements in a tuple in the same way as we do in lists and strings. Hence, we can access elements simply by indexing and slicing. Furthermore, the indexing is simple as in lists, starting from the index zero.


2 Answers

There isn't a way built in the language, because variable indexing on a heterogeneous type like a tuple makes it impossible for the compiler to infer the type of the expression.

You could use a macro that unrolls a for loop with variable indexing for a tuple if it is really, really necessary though.

If you are going to be using homogeneous tuples that require variable indexing, why not just use a fixed-length array?

like image 115
EvilTak Avatar answered Oct 21 '22 19:10

EvilTak


So, is there any way to get the ith value of vec?

No, there isn't. Since tuples can contain elements of different types, an expression like this wouldn't have a statically-known type in general.

You could consider using an array instead of a tuple.

like image 34
fjh Avatar answered Oct 21 '22 21:10

fjh