iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
1
Blockchain

區塊練起來-智能合約與DApp開發系列 第 6

[區塊練起來-智能合約與DApp開發] DAY 06 - Solidity 型別

貼心小語

上一篇學習了 Solidity 的基本結構,並使用 Truffle 來測試合約,這一篇將會深入講解 Solidity 有哪些型別可以使用喔~


型別介紹

在 Solidity 中有許多型別,有些是基本的型別,跟其他程式語言差不多的;有些則是特殊型別。

整數(Integer)

分為 有號整數無號整數 ,長度設定則是以8的倍數至256,如下:

int8 public num = -127;
int16 public num2 = 32767;
int256 public num3 = -3;
int public num4 = 4; //相當於int256

uint8 public num5 = 255;
uint public num6 = 6; //相當於uint256

布林(Boolean)

這個大家都不陌生吧!

bool public isTrue = true;
bool public isFalse = false;

字串(String)

在 HelloWorld 合約裡面有悄悄出現,在給定字串時,應使用雙引號而不是單引號。

string public message = "HelloWorld";

另外,在 Solidity 中,字串並 沒有 length 屬性,也 不能 用 index 的方式取得字元,如下:

string public message = "HelloWorld";
message.length; //error
message[0]; //error

位元組(Bytes)

有1~32位元組,如:bytes1, bytes32,有 length 屬性,可用來變更字串、讀取字串中的字元,算是很重要的型別。

bytes public buffer = "HelloWorld";

在字串變更或轉換時,遇到超過 1bytes 的字元時,那會發生問題,這部分需要注意一下。

陣列(Arrays)

可以設定 動態陣列靜態陣列

uint[] public arr; //動態陣列
uint[5] public arr2; //長度為5的靜態陣列
uint[2][2] arr3; //2行2列的二維陣列
arr.push(1); //添加1至arr

位址(Address)

用來位址訊息,如:EOA 帳戶。

address public owner = 0xfd9ab01f1B3BcA9Ff27FD4DB6069aE04c5f88664;

結構(Struct)

用來自定義資料格式的型別。

struct Profile {
  string name;
  uint8 age;
}
  
  Profile user = Profile({ name: "John", age: 40 });

列舉(Enum)

經常與 struct 搭配用。

enum Member {
  normal,
  VIP
}

struct Profile {
  string name;
  uint8 age;
  Member membership
}

Profile user = Profile({
  name: "John",
  age: 40,
  membership: Member.VIP
});

映射(Mapping)

可以把 mapping 視為是動態陣列,並可以透過 key 來查詢對應的 value ,且 key 只能是唯一的。
需要注意的是 key 的型別不能是 structenum
範例如下:

struct Profile {
  string name;
  uint8 age;
}

mapping(address => uint) public balances;
mapping(Profile => uint) public balances; //error

Float與Double

在 Solidity 中,並 沒有 這個型別,只有整數,我們不計較那小數目的


今日小結

將 Solidity 的資料型別整理一下:

  • 整數(Integer)
  • 布林(Boolean)
  • 字串(String)
  • 位元組(Bytes)
  • 陣列(Arrays)
  • 位址(Address)
  • 結構(Struct)
  • 列舉(Enum)
  • 映射(Mapping)
  • 沒有float/double

上一篇
[區塊練起來-智能合約與DApp開發] DAY 05 - HelloWorld合約
下一篇
[區塊練起來-智能合約與DApp開發] DAY 07 - Solidity 修飾詞
系列文
區塊練起來-智能合約與DApp開發31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言