Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
George Shuklin Avatar asked Oct 16 '25 16:10

George Shuklin


1 Answers

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

}
like image 155
E_net4 stands with Ukraine Avatar answered Oct 19 '25 12:10

E_net4 stands with Ukraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!