0
0
Blockchain / Solidityprogramming~5 mins

Reference types behavior in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Reference types let you work with data by pointing to where it is stored, not copying it. This helps save space and keep data consistent.

When you want multiple parts of your program to share and update the same data.
When working with large data structures to avoid copying them again and again.
When you want changes in one place to automatically show up everywhere else that uses the data.
When managing complex objects like accounts or contracts that need to stay linked.
When you want to pass data efficiently between functions without making copies.
Syntax
Blockchain / Solidity
type MyStruct = struct {
    value: int
}

let a = MyStruct(10)
let b = &a  // b is a reference to a
b.value = 20  // changes a.value too

Reference types store the address of the data, not the data itself.

Changing data through a reference changes the original data.

Examples
Here, y is a reference to the array x. Both share the same data.
Blockchain / Solidity
let x = [1, 2, 3]
let y = &x
// y points to the same array as x
// changing y changes x
acc2 is a reference to acc1. Changing acc2 changes acc1.
Blockchain / Solidity
struct Account {
    balance: int
}

let acc1 = Account(100)
let acc2 = &acc1
acc2.balance = 200
// acc1.balance is now 200
Sample Program

This program shows how changing the amount through wallet2 changes wallet1 because wallet2 is a reference.

Blockchain / Solidity
struct Wallet {
    amount: int
}

let wallet1 = Wallet(50)
let wallet2 = &wallet1

print("Before:", wallet1.amount)
wallet2.amount = 100
print("After:", wallet1.amount)
OutputSuccess
Important Notes

Be careful: changing data through one reference affects all references to it.

Reference types help save memory but require careful management to avoid bugs.

Summary

Reference types point to data location instead of copying data.

Changes through references affect the original data.

Useful for sharing and updating data efficiently.