Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get last element from vector

I have this simple piece of code:

fn main() {
    let mut blockchain: Vec<blockchain::Block> = Vec::new();

    let genesis_block = blockchain::create_block("genesis_block");

    blockchain::add_block_to_blockchain(&mut blockchain, genesis_block);
}

My error occurs here:

pub fn get_last_block(blockchain: &Vec<Block>) -> Block {
    return blockchain[blockchain.len() - 1];
}

It says:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

I am pretty new to rust, so can somebody explain me why this wont work?

I just trying to get the last element of this vector.

Should i pass the ownership of this vector instead of borrowing it?

EDIT: This is my result now:

pub fn get_last_block(blockchain: &Vec<Block>) -> Option<&Block> {
    return blockchain.last();
}

blockchain could be empty. I check with is_some if its returning an value

let block = blockchain::get_last_block(&blockchain);
if block.is_some() {
    blockchain::print_block(block.unwrap());
}

>Solution :

Since you are borrowing the vector, you can either:

  • return a reference to the block
  • clone the block
  • pop the block from the vec and return it (you would need to mutably borrow it instead, &mut)

Also, consider using an Option as return type, in case your vector is empty. By using this, you could directly call to last for example, this would return a reference & to the last Block:

pub fn get_last_block(blockchain: &Vec<Block>) -> Option<&Block> {
    blockchain.last()
}

Nitpick, you could use a slice instead of a Vec in the function signature:

fn get_last_block(blockchain: &[Block])...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading