---
title: 'Solidity WTF 101 8 ~ 10 單元'
lang: zh-tw
---
Solidity WTF 101 8 ~ 10 單元
===
:::info
:date: 2024/09/26
:::
[TOC]
## 課程學習
### 變數初始值
---
這邊大致介紹任何型別宣告的變數下他們的初始值為何。
```xml=
bool public _bool; // false
string public _string; // ""
int public _int; // 0
uint public _uint; // 0
address public _address; // 0x0000000000000000000000000000000000000000
enum ActionSet { Buy, Hold, Sell}
ActionSet public _enum; // 第1个内容Buy的索引0
function fi() internal{} // internal空白函数
function fe() external{} // external空白函数
<!-- 空白函數是指沒有任何功能的函數,它們只定義了函數本身,但沒有在函數體內執行任何操作。這些函數既不改變區塊鏈的狀態,也不傳回任何值 -->
```
### 引用類型初始值
```xml=
// Reference Types
uint[8] public _staticArray; // 所有成员设为其默认值的静态数组[0,0,0,0,0,0,0,0]
uint[] public _dynamicArray; // `[]`
mapping(uint => address) public _mapping; // 所有元素都为其默认值的mapping
<!-- 這邊mapping初始值是value的初始值 -->
// 所有成员设为其默认值的结构体 0, 0
struct Student{
uint256 id;
uint256 score;
}
Student public student;
```
### delete操作符
能夠讓已經改變的值,回到預設值,他不是清空。
:::warning
:information_source: 要注意它只會更改值,並不會動到長度,假設今天一個array是[1, 2, 3],使用後會變成[0, 0, 0]。
:::
### 常數
---
分為兩種`constant`和`immutable`,兩者在宣告後都沒有辦法進行修改,差別在於`immutable`能不先宣告值給他,可以之後給予。
```xml=
<!-- 先給予值 -->
uint256 public immutable IMMUTABLE_NUM = 9999999999;
<!-- 之後再給予 -->
address public immutable IMMUTABLE_ADDRESS;
<!-- 用此方法賦值 -->
constructor(){
IMMUTABLE_ADDRESS = address(this);
}
```
* `constant`变量初始化之后,尝试改变它的值,会编译不通过并抛出`TypeError: Cannot assign to a constant variable.`的错误。
* `immutable`变量初始化之后,尝试改变它的值,会编译不通过并抛出`TypeError: Immutable state variable already initialized.`的错误
### 控制流
---
有一些基本判斷已經了解就不多做贅述,這邊先講解`do-while`與`while`
* `while`會先進行判斷`do-while`不會
* 在相同判斷下`do-while`會比`while`多執行一次
#### 插入排序
```xml=
<!-- 要注意不從0開始算,因為有可能會成為負數-->
function insertionSort(uint[] memory a) public pure returns(uint[] memory) {
// note that uint can not take negative value
for (uint i = 1;i < a.length;i++){
uint temp = a[i];
uint j=i;
while( (j >= 1) && (temp < a[j-1])){
a[j] = a[j-1];
j--;
}
a[j] = temp;
}
return(a);
}
```