rust - 如何在 Rust 中使用 sha256 散列 sha256 的输出

标签 rust sha256 lifetime

我写了一些存在生命周期问题的使用rust 代码。

let mut sha256 = Sha256::new();
sha256.input_str(input.as_slice());

for i in range(0i,16) {
    println!("i == {}, hash == {}", i, sha256.result_str());
    let bytes = sha256.result_bytes().as_slice();
    sha256.input(bytes);
}

错误是:

$ cargo build && ./target/hello_world asdfasdf
   Compiling hello_world v0.1.0 (file:///home/chris/hello_world)
src/hello_world.rs:41:21: 41:42 error: borrowed value does not live long enough
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
                                          ^~~~~~~~~~~~~~~~~~~~~
src/hello_world.rs:39:27: 43:6 note: reference must be valid for the block at 39:26...
src/hello_world.rs:39     for i in range(0i,16) {
src/hello_world.rs:40         println!("i == {}, hash == {}", i, sha256.result_str());
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
src/hello_world.rs:42         sha256.input(bytes);
src/hello_world.rs:43     }
src/hello_world.rs:41:9: 41:53 note: ...but borrowed value is only valid for the statement at 41:8; consider using a `let` binding to increase its lifetime
src/hello_world.rs:41         let bytes = sha256.result_bytes().as_slice();
                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `hello_world`.

To learn more, run the command again with --verbose.

我怎样才能改变它,并且仍然让它有效地执行?

最佳答案

那是因为 result_bytes() 的结果在该行之后被丢弃,而 as_slice() 正在获取对它的引用。借用检查器不会让它发生。

为了让它工作,你应该这样写:

let mut sha256 = Sha256::new();
sha256.input_str(input.as_slice());

for i in range(0i,16) {
    println!("i == {}, hash == {}", i, sha256.result_str());
    let bytes = sha256.result_bytes();
    sha256.reset();
    sha256.input(bytes.as_slice());
}

希望对您有所帮助。

关于rust - 如何在 Rust 中使用 sha256 散列 sha256 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26220655/

相关文章:

rust - 在 Rust 中取消引用 Rc<Vec<T>> 混淆

rust - 如果不符合要求,即使应该满足

javascript - javascript 中的 HMAC SHA256 十六进制摘要

ssl - 如何在命令行上检查我的 SSL 证书是 SHA1 还是 SHA2

rust - 返回由闭包借用 self 产生的迭代器的函数的正确返回类型是什么

Rust:无法在线程之间安全地共享 impl 特征

rust - 为什么我在 "no ` 中收到错误 `executor` block_on` 尝试阻塞异步函数时?

react-native - 使用 sha256 响应 native

rust - 如何将闭包参数传​​递给具有生命周期参数的特征方法?

send - Send 特征的终身问题