gpt4 book ai didi

arrays - 使用 Rust 创建自定义类型 bytes32 作为 32 位宽的字节数组

转载 作者:行者123 更新时间:2023-11-29 08:36:32 26 4
gpt4 key购买 nike

bytes32 是一种类型,在 Vyper 中是一个 32 位宽的字节数组。以下来自https://github.com/ethereum/vyper/blob/master/docs/types.rst#32-bit-wide-byte-array :


32 位宽字节数组

关键字: bytes32这是一个 32 位宽的字节数组,在其他方面类似于字节数组。

示例:

# Declaration
hash: bytes32
# Assignment
self.hash = _hash

运算符

====================================  ============================================================
Keyword Description
==================================== ============================================================
``len(x)`` Return the length as an integer.
``sha3(x)`` Return the sha3 hash as bytes32.
``concat(x, ...)`` Concatenate multiple inputs.
``slice(x, start=_start, len=_len)`` Return a slice of ``_len`` starting at ``_start``.
==================================== ============================================================

其中x是字节数组,_start_len是整数值。


我想知道如何在 Rust 中创建这样一个 bytes32 作为自定义类型。要创建自定义类型,您可以使用结构,它是一个数组,但我不确定定义数组的最佳方法是什么。我想这样做:

struct Bytes32 {
bytes32: [0b00000000; 4]
}

但这显然不理想为了可读性,你必须使用一个特定的值,0b00000000

最佳答案

您可以使用自定义结构

我举了一个简单的例子。您应该调整它并为输入和输出制作一个包装器。

#[derive(Eq, PartialEq)]
struct Bytes32 {
pub store: Vec<[u8; 4]>,
}

impl Ord for Bytes32 {
fn cmp(&self, other: &Bytes32) -> Ordering {
for _i in 0..3 {
if other.store[_i] > self.store[_i] {
return Ordering::Greater;
}
if other.store[_i] < self.store[_i] {
return Ordering::Less;
}
}
Ordering::Equal
}
}

impl PartialOrd for Bytes32 {
fn partial_cmp(&self, other: &Bytes32) -> Option<Ordering> {
Some(self.cmp(other))
}
}

关于arrays - 使用 Rust 创建自定义类型 bytes32 作为 32 位宽的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49484135/

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