![](/img/trans.png)
[英]Why Rust compiler is not smart enough to detect the variable and function with same name?
[英]Rust: a struct and a function with the same name
可以創建同名的結構體和函數。 對於創建沒有::new()
樣板的結構可能很有用。 例如:
#[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);
}
::new()
一起使用?是的,這是不好的風格。 這不僅會使您混淆是導入 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
不,您應該使用::new()
或公開字段,以便用戶可以像這樣構建它:
let point = Point { x: 1, y: 2 };
不,它不會很快被刪除,因為它只是一個樣式/設計問題,不會以任何有意義的方式影響 Rust。 無論如何,人們不會喜歡你何時這樣做,因為它與我們都遵循的使第三方庫的集成更容易的一般准則相反。
如果您只想擁有一個命名元組,那么請改用命名元組結構:
#[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.