【Structs】
宣告 struct 在這裡的用途和 C 的語言一樣,如果是沒有學過 C/C++ 的話,可以把 struct 理解成一種比較低階的 C++, python 的 class。
定義一個 struct 之後會產生一種新的自定義、抽象、複雜的的資料型態。後我們就可以藉由這個資料型態宣告我們自己的結構變數。
struct User {
address id;
string name;
}
//Method 1 (argument order matters)
User("0xAio90....", "Mike");
//Method 2 (argument order does not matter)
User({name: "Mike", id: "0xAio90...."});就像是我們定義一個新的形態是車子,並且定義一台車子裡面要有的資料有:持有者(address)、品牌(string)、公升數(uint)。
此後就可以宣告一個資料型態為車子的變數 myCar,並定義這個變數裡面的每個型態。
struct Car {
address owner;
string brand;
uint cc;
}
myCar = Car({string: "Toyota", address: "0xAio90....", cc: 2000});Structs具有以下的性質:
在Solidity中不可以使用遞迴性的方式宣告變數,也就是說
struct的成員的型別不可是該struct。以structs取代objects可以達到gas consumption
我們可以組合
struct和mapping或甚至其他容器來建置些複雜的資料結構,像是以下例子是使用巢狀的資料結構(Nested Data Structures)來達成目的。
其他範例:
Last updated
Was this helpful?