gpt4 book ai didi

javascript - 如何在 borsh-js 中序列化枚举

转载 作者:行者123 更新时间:2023-12-05 03:30:37 26 4
gpt4 key购买 nike

尝试在 Rust 中序列化一个对象并在 JS 中反序列化它我们得到 000100000031 哈希值,在序列化之后:

pub enum Service {
Stackoverflow,
Twitter,
Telegram,
}
pub struct ServiceId {
pub service: Service,
pub id: ExternalId,
}

当试图在 JS 中反序列化时使用这个:

const Service = {
Stackoverflow: 0,
Twitter: 1,
Telegram: 2
}

class ServiceId {
constructor(service, id) {
this.service = service
this.id = id
}
}
const value = new ServiceId(Service.Stackoverflow, userId)

const schema = new Map([
[ServiceId,
{ kind: 'struct', fields: [['service', 'u8'], ['id', 'string']] }]
]);

反序列化后,我们得到了这个,但它是不正确的,因为我们在一个对象中有一个对象和一个冗余的id参数:

ServiceId { service: { service: undefined, id: '1' }, id: undefined }

首先可能是因为在 Rust 中我们有枚举类型,所以我们如何在 borsh-js 中使用枚举。其次,如果不是,为什么我们的结果不正确?

最佳答案

从文档中很难理解,但你需要像这样创建你的类,一切都会好起来的。

class ServiceId {
constructor({ service, id }) {
this.service = service
this.id = id
}
}
new ServiceId({ service: 'lol', id: 'kek' })

因此您需要将参数作为对象传递。

关于javascript - 如何在 borsh-js 中序列化枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70792718/

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