【问题标题】:How to iterate in a Rust element non-iterable?如何迭代不可迭代的 Rust 元素?
【发布时间】:2021-11-14 03:15:57
【问题描述】:

我正在尝试通过使用 for 循环的 API 创建的此变量的结果进行迭代(此处已注释,否则会出错):

    let create_account_instruction: Instruction = solana_sdk::system_instruction::create_account(
    &wallet_pubkey,
    &mint_account_pubkey,
    minimum_balance_for_rent_exemption,
    Mint::LEN as u64,
    &spl_token::id(),
    );
    println!("Creating the following instructions: {:?}", create_account_instruction);

    // for x in create_account_instruction {
    //     println!("{:?}", x)
    // }

这是我想要迭代的结果(仅供参考:那些私钥和公钥仅用于在 devnet 上进行测试):

Creating the following instructions: Instruction { program_id: 11111111111111111111111111111111, accounts: [AccountMeta { pubkey: ESCkgk5AfDC8cXd4KYjkUda1psCL8otfu8NvniUBiGhX, is_signer: true, is_writable: true }, AccountMeta { pubkey: Ah63GoKnnBicTELvfz2F9YvF9vaR51HR2BK3hJWwWE8x, is_signer: true, is_writable: true }], data: [0, 0, 0, 0, 96, 77, 22, 0, 0, 0, 0, 0, 82, 0, 0, 0, 0, 0, 0, 0, 6, 221, 246, 225, 215, 101, 161, 147, 217, 203, 225, 70, 206, 235, 121, 172, 28, 180, 133, 237, 95, 91, 55, 145, 58, 140, 245, 133, 126, 255, 0, 169] }

如果我尝试通过 for 循环遍历它(取消注释上述内容),我会收到此错误:

Compiling AmatoRaptor v0.1.0 (/home/joomjoo/Desktop/Tester)
error[E0277]: `Instruction` is not an iterator
--> src/main.rs:89:14
|
89  |     for x in create_account_instruction {
|              ^^^^^^^^^^^^^^^^^^^^^^^^^^ `Instruction` is not an iterator
|
= help: the trait `Iterator` is not implemented for `Instruction`
= note: required because of the requirements on the impl of `IntoIterator` for `Instruction`
note: required by `into_iter`
--> /home/joomjoo/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:234:5
|
234 |     fn into_iter(self) -> Self::IntoIter;
|     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain

我的问题是迭代结果的最简单方法是什么?

【问题讨论】:

  • 什么是“结果”?

标签: for-loop rust iterator rust-cargo


【解决方案1】:

Solana documentationInstruction是一个结构体:

pub struct Instruction {
    pub program_id: Pubkey,
    pub accounts: Vec<AccountMeta, Global>,
    pub data: Vec<u8, Global>,
}

您可以访问其属性,并对其进行迭代:

for x in create_account_instruction.data {
    ...
}

for x in create_account_instruction.accounts {
    ...
}

【讨论】:

  • 我都试过了,但是它要求我用“&”添加一个借用,比如:for x in &create_account_instructions.account...,但这只会在名为的特定部分内迭代(.data 或 .account),是否有遍历该结构中的所有项目? (例如获取program_id)。
  • @SkylerX,这是完全不可能的,因为它们甚至不是同一类型。你真正想做的是什么?
  • 我正在尝试打印出该结构中的所有元素,而不是让它们一起打印出来,因为它很难阅读和调试,所以我正在尝试找到一种打印方式它们从上到下以某种顺序逐一打印出来,而不是在多行上打印出来。
  • @SkylerX,您可以实现Display 为该类型的一些包装器(因为您不能为外来类型实现任何东西)。但无论如何,您都必须为每个字段手动完成。
猜你喜欢
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 2021-11-19
  • 1970-01-01
相关资源
最近更新 更多