Tuple Struct To Struct?

I've been working with Rust for a bit and have a question about the preferred method of tuple conversions. Let's say I have a struct A and a struct B. I'm working with a library that returns results as a Vec<(A, B)>. I want to store these results in a struct so I can access them by field name, instead of index. I've currently come up with this soluton.

struct A {
}

struct B {
}

struct C {
  a: A,
  b: B,
}

impl From<(A, B)> for C {
  fn from(item: (A, B)) -> Self {
    Self {
        a: item.0,
        b: item.1,
    }
  }
}

let data = items.map(C::from)
  .collect::<Vec<_>>();

Is this the preferred method to do this type of conversion in Rust? The only part that I don't like is the item.0 and item.1. Is there a cleaner way to do the conversion in my example then what I implemented?

This works:

impl From<(A, B)> for C {
    fn from((a, b): (A, B)) -> Self {
        Self { a, b }
    }
}
2 Likes

This is exactly what I was looking for. So basically by replacing item with (a, b), it lets you reference the fields by a name instead of index in a tuple?

Yes. Function parameters can use the same pattern-matching syntax as in let statements and match expressions, including destructuring of structs and tuples.

1 Like

Okay, good to know. Thanks for the help and the quick reply.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.