1. Visibility
1. Public -> can be used internally and externally
- can be used by metamask, or other contract can call the function
- publicly available for anybody to use it
2. private -> can be used within the contract only
- cannot be used on the blockchain
3. internal -> can be used within the contract and the other inheriting contracts
pragma solidity ^0.8.23;
contract BasicCalculator {
uint256 public result;
function add(uint256 a, uint256 b) internal {
result = a + b;
}
function subtract (uint256 a, uint256 b) internal {
result = a - b;
}
}
contract AdvancedCalculator is BasicCalculator {
function multiply(uint256 a, uint256 b) internal {
result = a * b;
}
function divide(uint256 a, uint256 b) internal {
result = a / b;
}
function performOperation(uint256 a, uint256 b, uint8 operation) internal {
if (operation == 0) add(a, b);
else if (operation == 1) subtract(a, b);
else if (operation == 2) multiply(a, b);
else if (operation == 3) divide(a, b);
else revert("Invalid operation");
}
}
4. external -> can be used only from external contracts or accounts
- save gas, can be only use outside the metamask
2. Mapping (ep.8)
- mapping is the [key] to open the door
- behind the door is [value]
pragma solidity ^0.8.23;
contract Mapping {
mapping(address => uint) public myMap;
function get(address _addr) public view returns (uint) {
return myMap[_addr];
}
function set(address _addr, uint _i) public {
myMap[_addr] = _i;
}
function remove(address _addr) public {
delete myMap[_addr];
}
}
3. Arrays (ep.10)
pragma solidity ^0.8.23;
contract Array {
uint[] public arr;
uint[] public arr2 = [1, 2, 3];
uint[10] public myFixedSizeArr;
string[5] public names
function get(uint i) public view returns (uint) {
return arr[i];
}
function getArr() public view returns (uint[]memory){
}
}
pragma solidity ^0.8.23;
contract ArrayExample{
uint[] public dynamaicArray;
uint[5] public fixedArray;
function addToDynamicArray(uint value) public {
dynamaicArray.push(value);
}
function getDynamicArrayLength() public view returns (uint) {
return dynamaicArray.length;
}
}
index
- is how we access the array, the key to open individual box
- always start with zero
[Reference] Nazweb