如何键入注释宏的返回值?

时间:2018-06-22 14:23:30

标签: types macros rust

请看一下这个人为设计的例子:

use std::io::{Read, Result};

macro_rules! read_u8 {
    ($r:expr) => {{
        let mut buf = [0; 1];
        $r.read_exact(&mut buf)?;
        Ok(buf[0])
    }};
}

fn t<R: Read>(r: &mut R) -> Result<u8> {
    let x = read_u8!(r)?;
    Ok(x)
}

fn main() {
    use std::io::Cursor;
    let mut x: Cursor<Vec<u8>> = Cursor::new(vec![1, 2, 3]);

    match t(&mut x) {
        _ => println!("Done"),
    }
}

如果您尝试run this example,则会得到:

error[E0282]: type annotations needed
  --> src/main.rs:12:13
   |
12 |     let x = read_u8!(r)?;
   |             ^^^^^^^^^^^^ cannot infer type for `_`

如何注释宏或调用站点以使其确定要返回范围内的Result

1 个答案:

答案 0 :(得分:3)

您可以使用内部变量声明来明确指示块的返回类型:

macro_rules! read_u8 {
    ($r:expr) => {{
        let mut buf = [0u8; 1];
        $r.read_exact(&mut buf)?;
        let ret: Result<u8> = Ok(buf[0]);
        ret
    }};
}

或通过强制转换:

macro_rules! read_u8 {
    ($r:expr) => {{
        let mut buf = [0; 1];
        $r.read_exact(&mut buf)?;
        Ok(buf[0])
    } as Result<u8>};
}