Question: why does Rust admit anonymous parameters in Traits?


#1

It is possible to omit parameter names when specifying trait methods:

trait T {
    fn foo(i32) -> i32 {
        92
    }
    fn bar(i32);
}

All other types of function declarations seem to require parameter names (fn types excluded):

// impl T {
//     fn foo(i32) -> i32 {
//         92
//     }
// }

// fn foo(i32) -> i32 {
//     92
// }

// extern {
//     fn foo(i32);
// }

What is the motivation for this design?


#2

Sounds like a bug.


#3

Quite possible. Here is the relevant piece of code from beloved parser.rs https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs#L1205-L1210.


#4

created an issue: https://github.com/rust-lang/rust/pull/29406


#5

In required methods, arg names are only there for documentation, so eliding them makes sense, which is why it is an option. It would be tricky (in the parser) to allow this elision for required but not provided methods, which is why elision is allowed for provided methods too.


#6

Yes, that makes sense. I was confused becase fn declarations in extern blocks do require names.

extern {
    // does not compile
    fn foo(i32);
}

It seems inconsistent.


#7

Wow turns out that fn declarations in traits are really special. They allow only a limited set of pattens, that is, I can

trait T {
    fn foo(& x: &i32) { }
}

trait T {
    fn foo(&& x: &&i32) { }
}

but I can’t

trait T {
    fn foo(&&& x: &&&i32) { }
}

trait T {
    fn foo((x, y): (i32, i32)) { }
}