2016-04-16 7 views
1

私のコードでは、match_num_works()のコードには優雅さがあります。私はStringと似たような配合を書いていますが、それを働かせることはできません。私はあまり優雅でないmatch_text_works()で終わる。構造体の文字列と文字列のパターンを一致させる方法

struct FooNum { 
    number: i32, 
} 

// Elegant 
fn match_num_works(foo_num: &FooNum) { 
    match foo_num { 
     &FooNum { number: 1 } =>(), 
     _ =>(), 
    } 
} 

struct FooText { 
    text: String, 
} 

// Clunky 
fn match_text_works(foo_text: &FooText) { 
    match foo_text { 
     &FooText { ref text } => { 
      if text == "pattern" { 
      } else { 
      } 
     } 
    } 
} 

// Possible? 
fn match_text_fails(foo_text: &FooText) { 
    match foo_text { 
     &FooText { text: "pattern" } =>(), 
     _ =>(), 
    } 
} 

答えて

5

そのおそらく「エレガント」または任意のよりよい..しかし、一つの選択肢ではない一致式に条件を移動することです:

match foo_text { 
    &FooText { ref text } if text == "pattern" =>(), 
    _ =>() 
} 

Working sample: Playpen link

+0

ありがとう!それはします。 – ebaklund

0

ご希望のパターンは、実際には&strで動作します。 Stringは、未露光の内部バッファを含むより複雑な値であるため、直接パターンマッチングすることはできません。

struct FooText<'a> { 
    text: &'a str, 
    _other: u32, 
} 

fn main() { 
    let foo = FooText { text: "foo", _other: 5 }; 
    match foo { 
     FooText { text: "foo", .. } => println!("Match!"), 
     _ => println!("No match"), 
    } 
} 

Playground

関連する問題