RE: RE: Solidity开发指南
You are viewing a single comment's thread from:

RE: Solidity开发指南

Words
296
Reading
2 min
Listen
Play
4M
  1. 映射 mapping
    类似python字典,主要用于存储。
    mapping(address => uint) public balances;
    balances[userAddr]访问数据
    mapping(uint => mapping(string => uint)) public people; //嵌套定义
mapping (bytes => Employee) bytesMapping;  //字节数组作为key
mapping (address => Employee) addressMapping; // address作为key
mapping (string => mapping(uint => Employee)) complexMapping;  // mapping作为value,是可以的。

//mapping可以设置id自增长以实现遍历。
uint public id = 0;
struct Article {
    string hash;
    address authoraddr;
    address[] voted;
    uint[] amount;
}
mapping(uint => Article) public articles;  //设置uint为id
event PostArticle(uint id, string t);
function postArticle(string memory _hash) public {       
    id ++; //id自增长,通过它来实现遍历。
    articles[id].hash = _hash;
    articles[id].authoraddr = msg.sender;
    emit PostArticle(id, _hash);
}
  1. 结构体 struct
    结构体是可以将几个变量分组的自定义数据类型
struct Student {
  string name;
  uint age;
  uint score;
  string sex;
}
Student stu1 = Student("lili", 18, 60, "girl");
Student stu2 = Student({name:"jim", age:20, score:80, sex:"boy"});

//可以存入数组以实现遍历
Student[] students;
  1. 字符串
    存储utf-8编码的字符串数据
    string a;
    string public str1 = "hello world"
    name = "" //空字符串

不能直接下标访问,没有length
solidity字符串功能相当弱小,要导入别的库
import "github.com/Arachnid/solidity-stringutils/strings.sol";

  1. 不定长字节数组,内容和长度均可修改
    bytes2.jpg

存储任意长度的字节数据
bytes bs;
bytes a = "hello"

可赋值,可动态调节,push,length
bytes public name = "helloworld";

bytes string可自由转换(bytes1不能直接转成sting, 需转成bytes):
bytes("helloworld")
string(bytes)

  1. 数组
    string, bytes, bytes1~bytes32本质上都是数组
    分为固定长度数组和动态长度数组
length
uint[7] arr  = [1,2,3,4,5,6,7];
arr[0]

, length,push
uint[] arr  = [1,2,3,4,5,6,7];

,
uint8[3][2] arrays = [[1,2,3], [2,3,5]] //arrays[2][3]

//可使用new关键字创建一个memory的数组,可以是任意的类型,地址、结构体、字符串等
returnData = new Delegator[](delegatorList.length);

function func1() public {
  uint[] memory v1 = new uint[](10);
  v1[0] = 1;
}
uint[] public arr1;   //storage
function func2() public {
  arr1 =  new uint[](10);
  arr1[0] = 2;
  arr1.push(15);
  arr1.length;
}


uint [10] tens;
uint [] us;

uint [] public u = [1, 2, 3];   // 生成函数
uint[] public b = new uint[](7);  //storage

.lengh
.pushmemory

.pop
delete0
delete arrays;
delete addrs[_a]; // 等价于: addrs[_a] = address(0)
  1. 合约类型
    import一个合约A后,在新合约中, A可以当做一个合约类型来使用,
    不过A中的函数执行环境不变,仍在A合约中执行。例如:B中导入A,A.send()仍会在A的环境中执行。
    eg:
contract A {
    function add (uint x, uint y) public pure returns (uint) {
        return x.plus(y);
    }
}

import "./A.sol"
contract B {
    function add2 (A a, uint x, uint y) public pure returns (uint) {
        return a.add(x,y)
    }
}
@lemooljiang: 映射 mapping | Ecency