如何将GenericArray< T,?>成相同长度的数组? [英] How can I turn a GenericArray<T, ?> into an array of the same length?

查看:63
本文介绍了如何将GenericArray< T,?>成相同长度的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm computing the SHA256 of a given data:

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

计算完后,我想将此值放入结构体的字段中:

After computing it, I want to put this value into a field of my struct:

let x = Hash { value: hashvalue };

但是, Hash 结构期望值的类型为 [u8;32] ,而我的 hashvalue 变量的类型为 GenericArray< u8,?> .如何将 hashvalue 转换为正确的类型?我试图将用作[u8;32] arr!,但这没有用.

However, the Hash struct expects the type of value [u8; 32], while my hashvalue variable is of type GenericArray<u8, ?>. How can I convert hashvalue into the correct type? I tried to use as [u8; 32] and arr! but it didn't work.

推荐答案

如果您不知道数组的长度,请将 GenericArray 转换为切片,然后将切片转换为数组(仅适用于长度小于等于32的数组在Rust 1.47之前):

If you don't know the length of the array, convert the GenericArray into a slice and then convert the slice into an array (only for arrays of length 32 or less 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);
}

另请参阅:

这篇关于如何将GenericArray&lt; T,?&gt;成相同长度的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆