George Shuklin
George Shuklin

Reputation: 7877

Unpacking structure to l-value tuple in Rust

I have following structure:

struct Pixel{x:f64, y:f64, dx:f64, dy:f64}

I got this structure as argument into function. I want to reduce typing and unpack it:

fn foo(pixel:Pixel){
    let (x, y, dx, dy) = pixel;
}

This code does not compile. Are there any syntax sugar to avoid endless pixel.x, pixel.dx, etc? I want to have some easy way to 'extract' ( to alias) values of structure into my function. And I want to avoid verbosity of let x = pixel.x; let dx = pixel.dx, etc.

Is there a concise way to do it?

Upvotes: 4

Views: 2207

Answers (1)

E_net4
E_net4

Reputation: 29983

An attentive reading of chapter 18 of The Rust Programming Language is recommended here. One can use pattern matching to destructure arrays, enums, structs, and tuples.

let Pixel { x, y, dx, dy } = pixel;

This can even be employed in a function's parameter arguments.

fn foo(Pixel { x, y, dx, dy }: Pixel) {

}

Upvotes: 10

Related Questions