1 数据、映射、结构体
1.1 struct:结构体
用于存储多个不同的数据类型。(有点像类)
contract FirstStruct{
//定义结构体
struct Info{
string phrase;
uint256 id;
address addr;
}
//使用结构体
function useStruct(string memory str,uint256 _id) public{
Info memory info = Info(str,_id,msg.sender);
}
}
msg是全局的变量,msg.sender用于获取谁发送交易的地址
1.2 array:数组
里面每个数据的数据类型都是相同的
contract FirstStruct{
//定义结构体
struct Info{
string phrase;
uint256 id;
address addr;
}
//定义数组
Info[] = infos;
function useStruct(string memory str,uint256 _id) public{
//使用结构体
Info memory info = Info(str,_id,msg.sender);
//使用数组
infos.push(info);
}
//数组遍历查找
function searchData(uint256 _id) public view returns(string memory){
for(uint256 i=0;i<infos.length;i++){
if(infos[i].id == _id){
//return string.concat(infos.string,"this contract from kite");
return infoMapping[_id].phrase;
}
}
return "Hello World";
}
}
1.3 mapping:映射
键值对形式存储(时间复杂度低)
contract FirstStruct {
//定义结构体
struct Info{
string phrase;
uint256 id;
address addr;
}
//定义mapping
//定义一个mapping数据结构,里面定义有两个数据,一个是id这个id指向的是一个数据结构为结构体的Info结构体、一个是info数据(里面的格式),这样的mapping数据结构定义的变量为infoMapping
mapping(uint256 id =>Info info) infoMapping;
function useStruct(string memory str,uint256 _id) public{
//使用结构体
Info memory info = Info(str,_id,msg.sender);
//使用结构体
infoMapping[_id] = info;
}
//mapping查找
function searchData(uint256 _id) public view returns(string memory){
//使用address来判断是否存在相应id的结构体
if(infoMapping[_id].addr == address(0x0)){
return "Hello World";
}else{
return infoMapping[_id].phrase;
}
}
}
2 智能合约工厂模式
2.1 引入合约
与JS类似
import {xxx} from './xxxx'
2.2 实例化合约
import {FirstStruct} from './FirstStruct.sol'
contract FirstStructFactory{
FirstStruct hy;
FirstStruct[] hys;
//创建合约
function createStruct() public {
hy = new FirstStruct();//new 出来的合约其实是一个地址,一个合约就是一个地址
hys.push[hy];
}
//获取合约
function getStruct(uint256 _index) public view returns(FirstStruct) {
return hys[_index]
}
}