2016-08-16 53 views
1

我試圖在Rust裏面玩多線程,我碰到過一些我認爲很平凡的東西。下面的代碼片段:爲什麼我不能嘗試! Mutex.lock?

use std::thread; 
use std::sync::{Arc, Mutex}; 

fn main() { 
    let vec: Vec<i32> = vec!(1, 2, 3); 
    let shared = Arc::new(Mutex::new(vec)); 

    let clone = shared.clone(); 

    let join_handle = thread::spawn(move || { 
     let mut data = clone.lock().unwrap(); 
     data.push(5); 
    }); 

    join_handle.join().unwrap(); 

    let clone = shared.clone(); 
    let vec = try!(clone.lock()); 

    println!("{:?}", *vec); 
} 

所以,我的問題是上線let vec = try!(clone.lock())。這會導致以下編譯器錯誤:

error: mismatched types [E0308] 
return $ crate :: result :: Result :: Err (
    ^
note: in this expansion of try! (defined in <std macros>) 
help: run `rustc --explain E0308` to see a detailed explanation 
note: expected type `()` 
note: found type `std::result::Result<_, _>` 

對我而言,這並沒有多大意義。 clone.lock()返回TryLockResult<MutexGuard<T>>,其實質上轉換爲Result<MutexGuard<T>, PoisonedError<MutexGuard<T>>,這意味着try!(clone.lock())應解析爲throw或MutexGuard<T>

我從根本上誤解了一些東西嗎?

回答

2

在rustc上運行'explain'會解釋這個錯誤 - 我以爲我已經有了,但我猜不是。

This error occurs when the compiler was unable to infer the concrete type of a 
variable. It can occur for several cases, the most common of which is a 
mismatch in the expected type that the compiler inferred for a variable's 
initializing expression, and the actual type explicitly assigned to the 
variable. 

For example: 

``` 
let x: i32 = "I am not a number!"; 
//  ~~~ ~~~~~~~~~~~~~~~~~~~~ 
//  |    | 
//  | initializing expression; 
//  | compiler infers type `&str` 
//  | 
// type `i32` assigned to variable `x` 
``` 

Another situation in which this occurs is when you attempt to use the `try!` 
macro inside a function that does not return a `Result<T, E>`: 

``` 
use std::fs::File; 

fn main() { 
    let mut f = try!(File::create("foo.txt")); 
} 
``` 

This code gives an error like this: 

``` 
<std macros>:5:8: 6:42 error: mismatched types: 
expected `()`, 
    found `core::result::Result<_, _>` 
(expected(), 
    found enum `core::result::Result`) [E0308] 
``` 

`try!` returns a `Result<T, E>`, and so the function must. But `main()` has 
`()` as its return type, hence the error. 

換句話說,錯誤不是與Mutex的類型;這是因爲我在主要功能中使用了try!; try!執行封閉函數返回一個Result<_, _>,但主函數必須返回()

如果我們看一下擴展代碼:

let vec = 
    match clone.lock() { 
     ::std::result::Result::Ok(val) => val, 
     ::std::result::Result::Err(err) => { 
      return ::std::result::Result::Err(::std::convert::From::from(err)) 
     } 
    }; 

之所以try!罵你是因爲return語句不match適用於塊,它適用於封閉的方法。

相關問題