1. 程式人生 > >ethereum(以太坊)(七)--列舉/對映/建構函式

ethereum(以太坊)(七)--列舉/對映/建構函式

pragma solidity ^0.4.10;

//列舉型別
contract enumTest{
    enum ActionChoices{Left,Right,Straight,Still}
                    //  0    1       2       3
    //input/output  uint
    ActionChoices public _choice;
    ActionChoices defaultChoice = ActionChoices.Straight;
    
    function setStraight(ActionChoices choice) public{
        _choice 
= choice; } function getDefaultChoice() constant public returns(uint){ return uint(defaultChoice); //2 } function isLeft(ActionChoices choice) constant public returns(bool){ if (choice == ActionChoices.Left){ return true; //0 } return false; //1,2,3
} } //建構函式 contract StructTest{ struct Student{ string name; uint sex; uint age; //uint year =15;ParserError: Expected ';' but got '=':Cannot be assigned within the constructor,unless use constructor public{} } Student public std1 = Student('lily',0,15); Student public std2
= Student({name:'lin',sex:1,age:17}); /* 0: string: name lin 1: uint256: sex 1 2: uint256: age 17 */ Student [] public students; function assgin() public{ students.push(std1); students.push(std2); std1.name ='eilinge'; /* 0: string: name eilinge 1: uint256: sex 0 2: uint256: age 15 */ } } //對映/字典 contract mappingTest{ mapping(uint => string) id_names; /* mapping (_key => _values) 鍵的型別允許除對映外的所有型別,如陣列、合約、列舉、結構體.值的型別無限制. 對映可以被視作一個雜湊表,其中所有可能的鍵已被虛擬化的建立,被對映到一個預設值(二進位制表示的零) 在對映表中,我們並不儲存建的資料,僅僅儲存它的keccak256雜湊值,用來查詢值時使用。 對映型別,僅能用來定義狀態變數,或者是在內部函式中作為storage型別的引用 */ constructor() public{ id_names[0x001] = 'jim'; id_names[0x002] = 'eilin'; } function getNamebyId(uint id) constant public returns(string){ string name = id_names[id]; return name; } } //修改器 pragma solidity ^0.4.10; contract modifierTest{ address owner=msg.sender; uint public v3; modifier onlyowner(address own) { require(own == owner); _; } function setv3() onlyowner(msg.sender) { v3 = 10; } }