githubEdit

Passing Data in Move: Value vs. Reference

Move uses pass-by-value for copies and pass-by-reference (& for reading, &mut for modifying) to data handling.

circle-info

For the latest RPC URL, please refer to the Supra Network Informationarrow-up-right page.

pass-by-value & pass-by-reference

In Move, when you pass a simple value as u64 to a function, you might be making a copy of it. This is called pass-by-value, for example:

fun add_one(value: u64) {
    // This doesn't change the original value!
    value = value + 1;
}

fun call_add_one() {
    let value = 10;
    // This is wrong as it makes a copy of value!
    add_one(value);

    // This will error out as the value is still 10!
    assert!(value == 11, 0);
}

So how do we modify the original value?

We need to pass a mut reference (&mut) to the value instead of the value itself. This is called pass-by-reference. This is similar to how you pass a pointer to a value in C/C++ or Rust.

There are two types of references in Move: references (&) and mutable references (&mut). The immutable reference (&) is often used to pass a value such as a vector to a function that only intends to read data instead of writing it. A function that takes a reference needs to explicitly declare:

You can also pass a reference to a struct and modify it:

Now, Write a function in Dinosaur_nest that returns the Gendna of the first Dinosaur in the DinosaurSwarm. Don’t forget the “acquires” declaration!