solidity中5种reference type: 1.struct 2.array 3.map 4.enum 5.string sames首字母缩写
一.stuct 多维的结构,结构体内还可以再包含字符串,整型,映射,结构体等复杂类型
1.设置struct 名称A struct A{ string title; string author; uint book_id; } 2.声明变量一样,声明一个变量book,指定类型为刚刚设置的struct名字A A book; 3.写入book = A(’’, ‘’, 1) //按照struct传参 // 第一种 book.push(A(titlename, ‘TP’, 1)); // 第二种 book.push(A({ title:titlename, author: ‘dhk’, book_id:2 })); // 第三种 A memory mybook; mybook.title = titlename; mybook.author = ‘newauthor’; mybook.book_id = 3; book.push(mybook);
4.读取book.book_id
pragma solidity ^0.5.0;
contract test {
struct A{
string title;
string author;
uint book_id;
}
A book;
function setBook() public {
book = A('Learn Java', 'TP', 1);
}
function getBookId() public view returns (uint) {
return book.book_id;
}
}
二、数组[] 1.设置数组类型: uint [] name; 2.数组和struct结合
pragma solidity ^0.5.0;
contract test {
struct A {
string title;
string author;
uint book_id;
}
A[] public book; //定义数组book,里面类型是A
function setBook(string memory titlename) public {
// 第一种
book.push(A(titlename, 'TP', 1));
// 第二种
book.push(A({
title:titlename,
author: 'dhk',
book_id:2
}));
// 第三种
A memory mybook;
mybook.title = titlename;
mybook.author = 'newauthor';
mybook.book_id = 3;
book.push(mybook);
}
function getBookId() public view returns (string memory) {
return book[1].author;
}
}
三、mapping mapping(key_type=> value_type) public A; 把struct放进map里面,一维对象放进多维对象。
pragma solidity ^0.5.0;
contract Store{
struct Product{
uint productId;
uint productValue;
}
mapping (uint=>Product) products;
function save() public {
Product memory product = Product(2,93);
products[120]=product;
}
function getPriceOfProductId(uint productId) public view returns (uint){
return products[productId].productValue;
}
}
四、enum 一维的 枚举类型,定好规则,到里面取。类型到咖啡厅,定好大中小杯。方便客户。
pragma solidity ^0.5.0;
contract Enumtest {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE } // 对应的:0,1,2
FreshJuiceSize choice;
FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;
function setLarge() public {
choice = FreshJuiceSize.LARGE; // 返回2
}
function getChoice() public view returns (FreshJuiceSize) {
return choice;
}
function getDefaultChoice() public pure returns (uint) {
return uint(defaultChoice); // 返回1
}
}
五、string 一维的 Solidity提供字节与字符串之间的内置转换,可以将字符串赋给 byte32类型变量。
pragma solidity ^0.5.0;
contract SolidityTest {
string data = "test";
bytes32 data2 = "test"; // 把string隐式转为bytes32
function mydata() public pure {
bytes memory bstr = new bytes(10);
string memory message = string(bstr); // 显式转为string
}
}
|