1

尝试在 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 中使用枚举。其次,如果不是,为什么我们的结果不正确?

4

1 回答 1

2

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

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

所以你需要将你的参数作为对象传递。

于 2022-01-20T23:13:38.263 回答