如何使用字符串在结构上实现 BorshDeserialize?

How can I implement BorshDeserialize on struct with a string?

尝试通过 Solana 程序构建时,出现此错误。任何人都可以告诉我如何序列化字符串,因为我在我的结构中使用字符串。或者,如果在 Solana 程序中无法序列化字符串,我应该使用什么而不是字符串?

结构:盒子

#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, PartialEq)]
pub struct Box {
    pub token_uris: [String; 3], 
    pub count: i32,
    pub title: String,
    pub description: String,
    pub image: String,
    pub price: i32,
    pub usd_price: i32,
    pub count_nft: i32,
    pub is_opened: bool,
}

错误日志:

15 | #[derive(Clone, Debug, BorshSerialize, BorshDeserialize, PartialEq)]
   |                                        ^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::string::String`
   |
   = note: required because of the requirements on the impl of `AnchorDeserialize` for `[std::string::String; 3]`
   = help: see issue #48214
   = note: this error originates in the derive macro `BorshDeserialize` (in Nightly builds, run with -Z macro-backtrace for more info)

Can anybody please tell me how can I serialize String, As I'm using String in my struct.

问题不在于您使用的是字符串或结构中的字符串,而是您在固定大小的数组中使用的是字符串,因此编译器特别指出:

for `[std::string::String; 3]`

没有

for `String`

如果你去阅读 the documentation for BorshDeserialize 你会发现:

impl<T> BorshDeserialize for [T; 3] where
    T: BorshDeserialize + Default + Copy, 

因此 BorshDeserialize 仅针对数组 Default + Copy 类型实现。由于 String 不是 Copy,自动推导无法工作。

修复是:

  • 不使用固定大小的数组
  • 或在您的结构上手动实现 BorshDeserialize 而不是尝试 derive()