2016-08-24 63 views
2

我有一個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)); 
} 

在那之後,我有額外的要求。我需要轉換爲兩種表示方法之一:

  1. N 70.152351
  2. N 70° 09' 08"

還有一個額外的標誌;當它是false,我需要的是這樣的:

  1. - --.------
  2. - --° -' -"

要實現的最簡單的方法,這將是:

fn format_lat(degree: f64, use_min_sec_variant: bool, is_valid: bool) -> String; 

不過,我不知道請參閱Rust標準庫中的任何免費函數。

也許我應該使用struct Latitude(f64)並實施to_string方法?或者,也許我應該實施一些其他特質?

+0

肯定有[標準庫中的免費函數](https://doc.rust-lang.org/std/cmp/#functions);你一定不會看得很遠。 – Shepmaster

+0

@Shepmaster也許他想'libc :: free()':P –

回答

5

您可以創建包裝種不同類型的格式,並返回他們的方法:

struct Latitude(f64); 
struct MinutesSeconds(f64); 

impl Latitude { 
    fn minutes_seconds(&self) -> MinutesSeconds { 
     MinutesSeconds(self.0) 
    } 
} 

impl fmt::Display for MinutesSeconds { 
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 
     write!(f, "latitude in a different format") 
    } 
} 

這與Path::display的想法是一樣的。

至於有效/無效的概念,聽起來像是你真的想要一個struct Latitude(Option<f64>),然後當它無效時提供None

2

您可以impl Latitude如果你需要傳遞的參數或impl ToString for Latitude如果你不這樣做:

use std::string::ToString; 

struct Latitude(f64); 

// If you need parameterisation on your conversion function 
impl Latitude { 
    // You'd probably use a better-suited name 
    pub fn to_string_parameterised(&self, use_min_sec_variant: bool) -> String { 
     // Conversion code 
     format!("{} {}", self.0, use_min_sec_variant) 
    } 
} 

// If you don't need parameterisation and want to play nicely with 100% of all code elsewhere 
impl ToString for Latitude { 
    fn to_string(&self) -> String { 
     // Conversion code 
     format!("{}", self.0) 
    } 
} 

fn main() { 
    let lat = Latitude(45.0); 
    println!("{}", lat.to_string_parameterised(false)); 
    println!("{}", lat.to_string()); 
} 
4

基本上你可以自由地做你想做的事。沒有更多關於你的目標的背景,任何方法對我來說似乎都足夠了。

個人而言,我會做它:

struct Latitude(f64); 

impl Latitutde { 
    pub fn format_as_x(&self, f: &mut fmt::Formatter) -> fmt::Result<(), Error> {} 

    pub fn format_as_y(&self, f: &mut fmt::Formatter) -> fmt::Result<(), Error> {} 
} 

加上Display特質+ to_format_x() -> String方便的功能。

format_as_y是國際海事組織最好的方法,因爲他們處理錯誤,可以採取任何格式化程序,並不需要分配String返回。

順便說一下,採取bool參數通常是反模式:布爾型陷阱。

相關問題