我正在计算给定数据的SHA256:
let hashvalue = sha2::Sha256::digest(&data);
计算完后,我想将此值放入结构体的字段中:
let x = Hash { value: hashvalue };
但是,Hash
结构期望值的类型为[u8; 32]
,而我的hashvalue
变量的类型为GenericArray<u8, ?>
。如何将hashvalue
转换为正确的类型?我尝试使用as [u8; 32]
和arr!
,但没有用。
答案 0 :(得分:3)
如果您不知道数组的长度,但长度不超过32个元素,请将GenericArray
转换为切片,然后将切片转换为数组:
use sha2::Digest; // 0.7.1
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);
}
另请参阅:
答案 1 :(得分:1)
根据the documentation for GenericArray
,我假设您可以使用long int temp = binary;
while(temp > 0) {
if(temp % 10 > 1) {
std::cout << "Input can only be binary!" << std::endl;
//do something
}
temp = temp / 10; //integer math will cut the lsb
}
,但是我没有设法对其进行编译。
非惯用的替代方法:
hashvalue.into()