Rust struct destructuring partial fields

#1
  1. I am aware of https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_structures.html

  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.
0 Likes

#2

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

#3

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

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

0 Likes

#4

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

0 Likes

#5

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

0 Likes

#6

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

1 Like

#7

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.)

0 Likes