2016-04-16 36 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

相关问题