Adding Elements with vector::push_back
vector::push_back allows you to add elements to a vector by passing a mutable reference (&mut), enabling dynamic storage updates within a module.
For the latest RPC URL, please refer to the Supra Network Information page.
vector::push_back: add all the things we’ve learned
We can add all the things we’ve learned so far to create a more complex module. One more thing you can do now that you know references: You can add an element to a vector using vector::push_back and pass a mutable reference to the vector.
Let’s modify spawn_dinosaur to add the new Dinosaur to the DinosaurSwarm’s vector of Dinosaurs instead of returning it.
module 0xcafe::dinosaur_nest {
use std::vector;
struct DinosaurGendna has key {
gendna_digits: u64,
gendna_modulus: u256,
}
struct Dinosaur has store {
gendna: u64,
}
struct DinosaurSwarm has key {
dinosaurs: vector<Dinosaur>,
}
fun init_module(cafe_signer: &signer) {
let gendna_digits = 10;
// 10^10. Move has no exponent operator, so the value is written out.
let gendna_modulus = 10000000000;
move_to(cafe_signer, DinosaurGendna {
gendna_digits: gendna_digits,
gendna_modulus: (gendna_modulus as u256),
});
move_to(cafe_signer, DinosaurSwarm {
dinosaurs: vector[],
});
}
public fun spawn_dinosaur(gendna: u64) acquires DinosaurSwarm {
let dinosaur = Dinosaur {
gendna: gendna,
};
let dinosaur_swarm = borrow_global_mut<DinosaurSwarm>(@0xcafe);
vector::push_back(&mut dinosaur_swarm.dinosaurs, dinosaur);
}
public fun get_gendna_digits(): u64 acquires DinosaurGendna {
borrow_global<DinosaurGendna>(@0xcafe).gendna_digits
}
public fun set_gendna_digits(new_gendna_digits: u64) acquires DinosaurGendna {
let dinosaur_gendna = borrow_global_mut<DinosaurGendna>(@0xcafe);
dinosaur_gendna.gendna_digits = new_gendna_digits;
}
public fun get_first_dinosaur_gendna(): u64 acquires DinosaurSwarm {
let dinosaur_swarm = borrow_global<DinosaurSwarm>(@0xcafe);
let first_dinosaur = vector::borrow(&dinosaur_swarm.dinosaurs, 0);
first_dinosaur.gendna
}
}Last updated on