gpt4 book ai didi

arrays - 如何将 GenericArray 转换为相同长度的数组?

转载 作者:行者123 更新时间:2023-12-02 09:05:18 24 4
gpt4 key购买 nike

我正在计算给定数据的 SHA256:

let hashvalue = sha2::Sha256::digest(&data);

计算后,我想将此值放入结构的字段中:
let x = Hash { value: hashvalue };

然而, Hash struct 需要值的类型 [u8; 32] , 而我的 hashvalue变量的类型是 GenericArray<u8, ?> .如何转换 hashvalue进入正确的类型?我尝试使用 as [u8; 32]arr!但它没有用。

最佳答案

如果您不知道数组的长度,请转换 GenericArray转换为切片,然后将切片转换为数组(仅适用于长度为 32 或更少的数组 before Rust 1.47 ):

use sha2::Digest; // 0.9.3
use std::convert::TryInto;

fn main() {
let hashvalue = sha2::Sha256::digest(&[3, 2, 6, 4, 3]);
let x: [u8; 32] = hashvalue.as_slice().try_into().expect("Wrong length");
println!("{:?}", x);
}
也可以看看:
  • How to get a slice as an array in Rust?
  • How to convert a slice into an array reference?
  • Is it possible to control the size of an array using the type parameter of a generic?
  • 关于arrays - 如何将 GenericArray<T, ?> 转换为相同长度的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59376378/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com