103 Fundamentals - Visibility, Mapping, Arrays (ep.6, 8, 10)

2023/12/15閱讀時間約 7 分鐘

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

// SPDX-License-Identifier: MIT
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]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

contract Mapping {
// Mapping form address to uint
mapping(address => uint) public myMap;

function get(address _addr) public view returns (uint) {
// Mapping always returns a value
// If the value was never set, it will return the default vaule
return myMap[_addr];
}

function set(address _addr, uint _i) public {
// Update the value at this address
myMap[_addr] = _i;
}

function remove(address _addr) public {
// Reset the value to the default value
delete myMap[_addr];
}
}

3. Arrays (ep.10)

  • a list of things
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

contract Array {
// Several ways to initialize an array
uint[] public arr;
uint[] public arr2 = [1, 2, 3];
// Fixed sized array, all elements intitialize to 0
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){

}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

contract ArrayExample{
// This is a dynamic array, it can be resized
uint[] public dynamaicArray;

// This is a fixed-size array, it cannot be resized
uint[5] public fixedArray;

function addToDynamicArray(uint value) public {
// Add a new element to the end of the array
dynamaicArray.push(value);
}

function getDynamicArrayLength() public view returns (uint) {
// Return the length of the dynamic array
return dynamaicArray.length;
}
}

index

  • is how we access the array, the key to open individual box
  • always start with zero

[Reference] Nazweb







尋大神腳印, 亦步亦趨。
留言0
查看全部
發表第一個留言支持創作者!