2017-08-25 66 views
7

Rust已決定禁止浮點文字的模式:Matching on floating-point literal values is totally allowed and shouldn't be #41255。它目前是一個警告,但在未來版本中將是一個嚴重的錯誤。替代匹配浮點數

我的問題是,然後,我該如何實現與下面的代碼?:

struct Point { 
    x: f64, 
    y: f64, 
} 

let point = Point {x: 5.0, y: 4.0}; 

match point { 
    Point {x: 5.0 , y} => println!("y is {} when x is 5", y), // Causes warning 
    _ => println!("x is not 5") 
} 

是現在不可能的等效例子嗎?我是否需要改變我對模式的看法?有沒有其他的方法來匹配它?

回答

13

您可以用一根火柴後衛:

match point { 
    Point { x, y } if x == 5.0 => println!("y is {} when x is 5", y), 
    _ => println!("x is not 5"), 
} 

這會將責任推回給你們,所以不會產生任何形式的警告。

Floating point equality is an interesting subject though ...所以我會建議你進一步研究它,因爲它可能是錯誤(我想象的鐵鏽核心團隊不希望對陣浮點值的原因)的來源。