This function takes 1 argument but 0 arguments were supplied expected 1 argument

Please what can I pass in place of &self in my add_block function I assume that's what's causing this error?

/// main.rs
mod models;

fn main() {
    models::blockchain::Blockchain::add_block()
}
/// ./models/blockchain.rs

use chrono::prelude::*;
use super::block::Block;
use super::block::BlockHash;

pub type Blocks = Vec<Block>;

// `Blockchain` A struct that represents the blockchain.
pub struct Blockchain {
    pub genesis_block: Block,
    pub chain: Blocks,
}

impl Blockchain {
    pub fn new() -> Blockchain {
        // First block in the chain
        let mut genesis_block = Block {
            index: 0,
            timestamp: Utc::now().timestamp_millis() as u64,
            prev_hash: BlockHash::default(),
            hash: BlockHash::default()
        };

        genesis_block.hash = genesis_block.calculate_hash();

        // Create chain starting from the genesis chain
        let mut chain = Vec::new();
        chain.push(genesis_block.clone());

        // Create Blockchain Instance
        let blockchain = Blockchain {
            genesis_block: genesis_block,
            chain: chain,
        };

        blockchain
    }

    pub fn add_block(&self) {
        println!("{:?}", self.chain.len());
    }
}

You need to pass in an instance of the Blockchain object. Normally this is done using method syntax.

let bc = Blockchain::new();
bc.add_block();

Methods are just functions where self.method() is syntactic sugar for method(&self) so you can pass it in manually. This trick can be helpful in some circumstances, although it isn't very idiomatic.

let bc = Blockchain::new();
Blockchain::add_block(&bc);
2 Likes

Thank you.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.