Is there any usecase for named arguments in fn pointer?

MaybeNamedParam :
OuterAttribute* ( ( IDENTIFIER | _ ) : )? Type

src: https://doc.rust-lang.org/reference/types/function-pointer.html

pub type F = fn(a: u8); // this compiles, but what is `a` for?

I didn't know you could do that, but presumably it is so that when writing a complex fn type you can give names to each parameter for documentation.

Unfortunate that Fn traits don't allow this.

1 Like

I've looked into this before, but I don't think I found anything definitive. My guess is also that it can be a form of documentation. And my guess for why the Fn traits do not is that in unsugared form, the argument types are trait type parameters, which also do not have names.

1 Like

I didn't either until I find FunctionPointer in rustdoc_types - Rust and Function in rustdoc_types - Rust share the same FnDecl in rustdoc_types - Rust in which named arguments are allowed.

(And thus if no named argument in fn pointers, the name will default to _, but I guess the documentation excludes the default case, otherwise you'll see unusual fn(_: Type) ).

Thanks for reminding me the name is useful when it's not _. The HTML output of rustdoc indeed shows the non-default name.

20240314114231
20240314114244


Correct. Fn* trait carries GenericArgs::Parenthesized , so the inputs of a Parenthesized GenericArg are Types, but named arguments are not Types. They are part of FnDecl in rustdoc_types - Rust

pub enum GenericArgs {
    Parenthesized {
        inputs: Vec<Type>, // not Vec<(String, Type)> as FnDecl does
        output: Option<Type>,
    },
    ...
}
pub struct FnDecl {
    pub inputs: Vec<(String, Type)>,
    ...
}

Great writings. :heart:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.