简体   繁体   中英

Rust: a struct and a function with the same name

It is possible to make a struct and a function with the same name. It might be useful for creating a struct without ::new() boilerplate. For example:

#[derive(Debug)]
struct Point { 
    x: i32, 
    y: i32,
}

fn Point(x: i32, y: i32) -> Point {
    Point { x, y }
}

fn main() {
    let point = Point(1, 2);
    println!("{:?}", point);
}
  • Is it considered a bad style?
  • Should I use it instead or along with ::new() ?
  • Are there any plans to deprecate this feature?

Yes, it is bad style. Not only does it make it confusing whether you imported a struct Point or a function with identical name, it is also going against general naming conventions:

warning: function `Point` should have a snake case name
 --> src/main.rs:7:4
  |
7 | fn Point(x: i32, y: i32) -> Point {
  |    ^^^^^ help: convert the identifier to snake case: `point`
  |
  = note: `#[warn(non_snake_case)]` on by default

No, you either should be using ::new() or make fields public, so user can build it like this:

let point = Point { x: 1, y: 2 };

And no, it won't be removed anytime soon, because it is only a style/design issue, not something that impacts Rust in any meaningful way. Regardless, people won't like when you'll do it, because it is the opposite of general guidelines that we all follow to make integration of third party libraries easier.


If your intention is just to have a named tuple, then please use a named tuple struct instead:

#[derive(Debug)]
struct Point(i32, i32);

fn main() {
    let p = Point(1, 2);
    println!("{:?}", point); // Point(1, 2)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM