首页 > 解决方案 > 在 Rust 中,将文件读取的数据保持在范围内的正确方法是什么?

问题描述

所以,我试过:

log("Loading haystack.");
// total_lines read earlier
let mut the_stack = Vec::<primitive_types::U256>::with_capacity(total_lines);
if let Ok(hay) = read_lines(haystack) { // Get BufRead
  for line in hay { // Iterate over lines
    if let Ok(hash) = line {
      the_stack.push(U256::from(hash));
    }
  }
}
log(format!("Read {} hashes.", the_stack.len()));

错误是:

$ cargo build
   Compiling nsrl v0.1.0 (/my_app)
error[E0277]: the trait bound `primitive_types::U256: std::convert::From<std::string::String>` is not satisfied
  --> src/main.rs:55:24
   |
55 |         the_stack.push(U256::from(hash));
   |                        ^^^^^^^^^^ the trait `std::convert::From<std::string::String>` is not implemented for `primitive_types::U256`
   |
   = help: the following implementations were found:
             <primitive_types::U256 as std::convert::From<&'a [u8; 32]>>
             <primitive_types::U256 as std::convert::From<&'a [u8]>>
             <primitive_types::U256 as std::convert::From<&'a primitive_types::U256>>
             <primitive_types::U256 as std::convert::From<&'static str>>
           and 14 others
   = note: required by `std::convert::From::from`

hash如果我有一个字符串文字而不是变量,则此代码有效,例如"123abc".

我想我应该能够使用 implementation std::convert::From<&'static str>,但我不明白我是如何保持hash在范围内的?

我觉得我想要实现的是一个非常正常的用例:

我错过了什么?

标签: rustscope

解决方案


几乎想要类似的东西,

U256::from_str(&hash)?

&strFromStrtrait中有一个转换,称为from_str. 它返回一个Result<T, E>值,因为解析字符串可能会失败。

我想我应该能够使用 implementation std::convert::From<&'static str>,但我不明白我是如何将 hash 保持在范围内的?

您不能将哈希值保持在'static生命周期的范围内。看起来这是一种允许您在程序中使用字符串常量的便捷方法——但实际上它只不过是U256::from_str(&hash).unwrap().

然而……</h2>

如果你想要一个 SHA-1,最好的类型可能是[u8; 20]或者可能是[u32; 5].

你想要一个 base 16 解码器,比如base16::decode_slice。以下是实际效果:

/// Error if the hash cannot be parsed.
struct InvalidHash;

/// Type for SHA-1 hashes.
type SHA1 = [u8; 20];

fn read_hash(s: &str) -> Result<SHA1, InvalidHash> {
    let mut hash = [0; 20];
    match base16::decode_slice(s, &mut hash[..]) {
        Ok(20) => Ok(hash),
        _ => Err(InvalidHash),
    }
}


推荐阅读