2017-04-10 91 views
2

我有一個非常簡單的方法。第一個參數需要向量組件(「A」,5,0),我會將它與另一個向量的每個元素進行比較,以查看它們是否具有相同的(_,5,_),然後打印出找到的元素的字符串。如何修復缺少的生命週期說明符?

比較( 「A」,5,0)和( 「Q」,5,2)應該打印出來問:

fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) { 
    let mut foundString = ""; 

    for i in 0..vector.len() { 

     if y1 == vector[i].1 { 
      foundString = vector[i].0; 
     } 

    } 
    foundString  
} 

不過,我得到這個錯誤

error[E0106]: missing lifetime specifier 
--> src/main.rs:1:80 
    | 
1 | fn is_same_space(x: &str, y1: i32, p: i32, vector: &Vec<(&str, i32, i32)>) -> (&str) { 
    |                    ^expected lifetime parameter 
    | 
    = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or one of `vector`'s 2 elided lifetimes 
+1

的這裏的一點是,你回來多數民衆贊成由*人*擁有的'&str'。編譯器想知道某人是誰,所以它可以知道'&str'指向的內存預期會存活多久。你需要告訴編譯器:「只要在」 – turbulencetoo

回答

5

通過指定一輩子

fn is_same_space<'a>(x: &'a str, y1: i32, p: i32, vector: &'a Vec<(&'a str, i32, i32)>) -> (&'a str) 

這只是衆多可能的解釋之一是您可能^ h ave意味着功能可以做,因此這是一個非常保守的選擇 - 它使用所有參考參數的統一生命週期。

也許你想返回一個字符串,只要x或只要vector或只要vector內的字符串;所有這些都可能是有效的。


強烈建議你回去重讀The Rust Programming Language。它是免費的,面向初學者Rust,它涵蓋了所有使Rust獨一無二且對程序員來說很新穎的東西。很多人花了很多的時間在這本書上,它回答了很多初學者這樣的問題。

具體來說,您應該閱讀的章節:

甚至還有一個second edition in the works,與像章節:


爲了好玩,我會重寫你的代碼使用迭代器:

fn is_same_space<'a>(y1: i32, vector: &[(&'a str, i32, i32)]) -> &'a str { 
    vector.iter() 
     .rev() // start from the end 
     .filter(|item| item.1 == y1) // element that matches 
     .map(|item| item.0) // first element of the tuple 
     .next() // take the first (from the end) 
     .unwrap_or("") // Use a default value 
} 
+0

「中傳遞的引用啊,謝謝你,先生,我將返回的'&str'將一直存在。我知道我應該閱讀這本書,但我更多的是先做代碼,然後問問題類型的人。正如你所看到的,我的類型推斷是拖延。我知道這是非常糟糕的做法,應該糾正我的習慣。謝謝 –

+0

@bossrevs:我知道這種感覺;當我看到一個編程語言「book」以* syntax *頁面開始時,我覺得我需要嘔吐。這很無聊,毫無興趣,我會在自己走的時候自然地挑選這些東西。新的[Rust Book,2nd edition](http://rust-lang.github.io/book/second-edition/index.html)雖然不同,這是非常實際的體驗,隨着例子的發展。我真的建議檢查一下,至少直到所有權/借款章節(第二章肉章)。 –

2

於是問題就來了一個事實,即vector有兩個推斷的壽命,一個是vector本身(&Vec部分)和一個用於向量內&str刪除多餘的括號。你也有一個推斷的生命週期x,但這真的是無關緊要的。

要解決它,只需指定返回&str生活,只要在載體中&str

fn is_same_space<'a>(      // Must declare the lifetime here 
    x: &str,         // This borrow doesn't have to be related (x isn't even used) 
    y1: i32,         // Not borrowed 
    p: i32,         // Not borrowed or used 
    vector: &'a Vec<(&'a str, i32, i32)>  // Vector and some of its data are borrowed here 
) -> &'a str {        // This tells rustc how long the return value should live 
    ... 
} 
+1

'&Vec <(&'a str,i32,i32)>'(或者更好,'&[(&'a str,i32,i32)]',請參閱http://stackoverflow.com/q/40006219/155423 )應該夠了。容器的壽命是無關緊要的。 – Shepmaster

+0

@Shepmaster謝謝你的建議,我沒有想過用切片代替。我還是比較新的生鏽和嘗試學習。我認爲我通過回答問題了解了很多Haskell,所以我應該對Rust進行相同的處理。看起來它已經在工作=) – bheklilr

+0

我更新了該評論,並附有「爲什麼」的鏈接。我出於同樣的原因開始回答Rust問題,所以我明白你來自哪裏! – Shepmaster