Unpacking struct members simultenously


#1

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?


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


#3

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

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

#4

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


#5

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);
}

#6

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


#7

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