我有一個f64
形式的度數緯度,我需要將它轉換爲String
。起初,我想過實施Display
,像這樣:什麼是慣用的Rust方法將值格式化爲多種字符串?
struct Latitude(f64);
impl fmt::Display for Latitude {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", if self.0 > 0. { "N" } else { "S" }, self.0)
}
}
fn main() {
let lat: f64 = 45.;
println!("{}", Latitude(lat));
}
在那之後,我有額外的要求。我需要轉換爲兩種表示方法之一:
N 70.152351
N 70° 09' 08"
還有一個額外的標誌;當它是false
,我需要的是這樣的:
- --.------
- --° -' -"
要實現的最簡單的方法,這將是:
fn format_lat(degree: f64, use_min_sec_variant: bool, is_valid: bool) -> String;
不過,我不知道請參閱Rust標準庫中的任何免費函數。
也許我應該使用struct Latitude(f64)
並實施to_string
方法?或者,也許我應該實施一些其他特質?
肯定有[標準庫中的免費函數](https://doc.rust-lang.org/std/cmp/#functions);你一定不會看得很遠。 – Shepmaster
@Shepmaster也許他想'libc :: free()':P –