0

I want to initialize two fields from a tuple returned from a function:

#[derive(Clone, Copy, Debug)]
struct Point {
    x: f64,
    y: f64,
    z: f64,
}

fn f() -> (f64, f64) {
    (5., 6.)
}

fn main() {
    let mut p = Point {
        x: 1.,
        y: 2.,
        z: 3.,
    };
    println!("{:?}", p);
    match f() {
        (x, y) => {
            p.x = x;
            p.y = y;
        }
    }
    println!("{:?}", p);
}

The obvious code (p.x, p.y) = f() did not compile so I have to use match. Do you have any idea how to make the match assignment simpler to read?

I want to

  1. Call f only once per assignment of the two fields
  2. Have f on the right side, and p.x and p.y and the left side, not how it is in match now
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103

1 Answers1

1

How's this?

let (x, y) = f();
p.x = x;
p.y = y;

You can put similar patterns in lets that you can put in matches.

paholg
  • 1,910
  • 17
  • 19