2016-08-24 1 views
2

度の度数がf64で、Stringに変換する必要があります。最初に私はこのように、Displayの実装について考えた:その後値を複数の種類の文字列にフォーマットする慣用的な方法は何ですか?

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)); 
} 

、私は追加の要件があります。私は2つの表現のいずれかに変換する必要があります。

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

追加のフラグもあります。これを実装するための最も簡単な方法はなり

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

:それはfalseあるとき、私のようなものが必要

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を割り当てる必要がないため、IMOの最良の方法です。

ところで、bool引数を取ることは、通常、アンチパターン:ブールトラップです。

関連する問題