为什么不能将切片更改为H512?

时间:2019-08-05 10:53:12

标签: curl types rust

我正在使用primitive_type条板箱,并使用rust-curl发出Http请求。

https://docs.rs/primitive-types/0.3.0/primitive_types/struct.H512.html https://docs.rs/curl/0.5.0/curl/easy/struct.Easy.html

pub fn hoge() {
    let param = "http://someurl.com/api/";
    let mut handle = Easy::new();
    let mut r = String::new(); 
    handle.url(&param.to_string()).unwrap();
    handle.post(true).unwrap();
    {
        let mut transfer = handle.transfer();
        transfer.write_function(|new_data| {
            r = String::from_utf8(Vec::from(new_data)).unwrap(); 
            Ok(stdout().write(new_data).unwrap())
        }).unwrap();
        transfer.perform().unwrap();
    }
    let b = H512::from_slice(&r.as_bytes());
}

它变成错误:

thread 'main' panicked at 'assertion failed: `(left == right)`
left: `132`,
right: `64`', /Users/hogehoge/.cargo/registry/src/github.com-1ecc6299db9ec823/primitive-types-0.3.0/src/lib.rs:68:1
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

看起来参数长度不匹配,但是有什么最好的方法可以返回H512类型吗?

1 个答案:

答案 0 :(得分:0)

就是这样解决的:

pub fn hoge() -> std::io::Result<(H512)> {
    let param = "http://someurl.com/api/";
    let mut handle = Easy::new();
    let mut r = String::new();
    handle.url(&param.to_string()).unwrap();
    handle.post(true).unwrap();
    {
        let mut transfer = handle.transfer();
        transfer.write_function(|new_data| {
            r = String::from_utf8(Vec::from(new_data)).unwrap();
            Ok(new_data.len())
        }).unwrap();
        transfer.perform().unwrap();
    }
    let r = r.replace("\"","").replacen("0x", "", 1);
    let result = H512::from_slice(&hex::decode(&r).expect("decode failed"));
    Ok(result)
}

还有更好的方法吗?