2014-09-13 71 views
5

考慮下面的例子誤差在模式匹配

​​

我得到這個誤差

error: the type of this value must be known in this conntext                                        
true => str.chars().map(|x| x.to_lowercase()).collect().as_slice() 
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

我有點混亂「類型,此值必須在此上下文中被稱爲」編譯器是否知道函數定義中str的類型是&str?我在這裏錯過了什麼?

回答

4

錯誤的位置可能令人困惑,這裏的問題是collect方法。它對於任何FromIterator都是通用的,在這種情況下,編譯器cat會推斷出類型(編譯器會看到的是您需要某種類型X實現FromIterator,它具有生成& str的as_slice方法)。

該代碼的第二個問題是您試圖從匹配語句中返回對本地值(收集結果)的引用。你不能這樣做,因爲該值具有該塊的生命週期並在之後被釋放,所以返回的將是無效的。

一個可行的解決方案(但它需要轉換& STR爲String):

fn main() { 
    f("hello", true); 
} 

fn f(str: &str, sen: bool) { 
    let s: String = match sen { 
     false => str.to_string(), 
     true => str.chars().map(|x| x.to_lowercase()).collect() 
    }; 
    println!("{}", s); 
} 

我不知道你想到底要實現什麼,但在MaybeOwned看看這是否是一個函數返回一個片(&str)或String

+0

謝謝。我最終使用臨時變量來存儲'String'並將其綁定到'temp_var.as_slice()'。不知道是否有更好的方法。 – 2014-09-13 11:56:19