Unpacking struct members simultenously

Ok so let's say I have a struct and a method

struct UserLogin {
    email: String,
    password: String
}

fn abc(email: String, password: String);

What I want is to call the function without any copying, however there does not seem to be any way for unpacking the struct. How can I achieve this?

let UserLogin { email, password } = thing_to_unpack;
abc(email, password);

However, unless you actually need to take ownership of those strings, the general advice is to just take &str parameters. Then you'd just call abc(&thing.email, &thing.password).

2 Likes

Beside that, you can also irrefutably match on the whole struct:

fn abc(UserLogin { email, password }: UserLogin) {}
1 Like

where in there is the actual value of the struct to unpack?

pattern bindings are not allowed after an @, so you can't give a name to the whole struct too. So if you call that function, only the struct fields names are usable.

Edit: a complete usage example:

struct UserLogin {
    email: String,
    password: String
}

fn abc(UserLogin { email, password }: UserLogin) {
    println!("{}", email);
    println!("{}", password);
}

fn main() {
    let u = UserLogin { email: "you@nl.net".into(),
                        password: "123456".into() };
    abc(u);
}
2 Likes

In @leonardo's example, you would call it with the whole struct to be unpacked, abc(some_user_login).

Thanks for the clear up, never had to do this before and had no idea it exists.

1 Like