2016-08-16 3 views
1

나는 Rust에서 멀티 쓰레딩에 대해 놀려고하고 있는데, 나는 사소한 것으로 생각할만한 것을 발견했다. 여기 코드는 다음과 같습니다왜 시도 할 수 없습니까! 뮤텍스. 록?

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의 종류 아니다 main 함수 내에서 try!을 사용하고 있기 때문입니다. try!은 enclosing 함수가 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)) 
     } 
    }; 

returnmatch에서 블록에 적용되지 않기 때문에 당신의 try! 고함이 이유는, 그것을 둘러싸는 방법에 적용됩니다.

관련 문제