简体   繁体   English

Rust:一个结构体和一个同名的函数

[英]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.对于创建没有::new()样板的结构可能很有用。 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() ?我应该使用它还是与::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:这不仅会使您混淆是导入 struct Point还是具有相同名称的函数,而且还违反了一般命名约定:

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:不,您应该使用::new()或公开字段,以便用户可以像这样构建它:

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.不,它不会很快被删除,因为它只是一个样式/设计问题,不会以任何有意义的方式影响 Rust。 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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