Skip to content

Wildcard pattern in function parameters. #848

@OnlyLys

Description

@OnlyLys

I noticed that the section on wildcard patterns says that:

Unlike identifier patterns, it does not copy, move or borrow the value it matches.

However for a function parameter, any arguments that match the wildcard are still consumed by the function:

fn main() {
    let s = String::from("Hello");
    f(s);

    // Won't compile since `s` was moved. 
    println!("{}", s);
}

fn f(_: String) {}

One explanation I had in my head was that function arguments are moved into the function's "stack frame" first, before being bound to parameters. So even though _ does not bind to s, s will still be moved into the function's scope and thus be "consumed".

However, I wasn't able to find any documentation of argument passing in the reference.

I'm willing to do any write-ups to update the documentation if someone can point me at the right direction.

Activity

ChrisCho-H

ChrisCho-H commented on Aug 7, 2024

@ChrisCho-H

How's the status of this issue? If the wildcard pattern exists in function parameter with the type of data which requires allocation into heap memory, it's ownership is moved.

mattheww

mattheww commented on Aug 7, 2024

@mattheww
Contributor

For what it's worth, the Reference's current description of how argument passing works is under "Function body" in functions.md:

The block of a function is conceptually wrapped in a block that binds the
argument patterns and then returns the value of the function's block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @ehuss@mattheww@OnlyLys@ChrisCho-H

      Issue actions

        Wildcard pattern in function parameters. · Issue #848 · rust-lang/reference