Rust struct destructuring partial fields

  1. I am aware of

  2. When destructuring:

pub struct Foo {
  x: i32, y: i32, z: i32

Is it possible to only grab a subset of the fields, i.e.

pub fn bar(foo: Foo) {
  let Foo {x, y} = foo;
  1. Right now, the answer appears to be no, but it seems surely there are times when we only want a subset of the fields.

To ignore the remaining fields use .. :

let Foo {x, y, ..} = foo;

If you meant only pass a subset of fields to the function,there is no way to do that.

1 Like

.. is precisely what I was looking for. Thanks!

I tried _, but didn’t think to try ..

If you really wanted to you could use _ but then you have to write
let Foo {x, y, z: _} = foo;

No, .. is much better, as z: _ is O(N) where N = number of unused fields

not true at all they both compile to the same (even on not optimized builds) look here

1 Like

O(N) refers to # of chars in the source code, not run time. (The motivation behind the question is to save chars + reduce width of the line.)