2016-08-16 10 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())は、スローまたは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<_, _>ですが、main関数は()を返す必要があります。

我々が拡大したコードを見れば:

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)) 
     } 
    }; 

return文がmatchのブロックには適用されませんので、try!はあなたに叫ぶ理由があり、それが囲む方法に適用されます。

関連する問題