Home > OS >  How to iterate in a Rust element non-iterable?
How to iterate in a Rust element non-iterable?

Time:09-23

I'm trying to iterate trough the results of this variable created from an API with a for loop (here commented or it will give an error):

    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)
    // }

Here is the results I would like to iterate trough (FYI: Those private and public keys are just for test on 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] }

If I try to iterate trough it via for loop (uncommenting the above), I get this error:

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

My question is what is the easiest way to iterate trough the results?

CodePudding user response:

From the Solana documentation, Instruction is a struct:

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

You can access its attributes, and iterate over them:

for x in create_account_instruction.data {
    ...
}

or

for x in create_account_instruction.accounts {
    ...
}
  • Related