区块链相关技术——solidity语法

Int&与uint类型

   int代表有符号的整数,也就是说可以带负数。

   uint代表没有符号的整数,也就是说是从0开始的正整数

    uint8 代表2的8次方

  uint256代表2的256次方

  uint默认为uint256

 int8代表-2的7次方到2的7次方

 int默认为256

 

pragma solidity ^0.4.4;
contract DemoTypes {
  function f(uint a) returns (uint b)
  {
    uint result = a * 8;
    return result;
  }
}
contract DemoTypes {
  function f2(int width, int height) returns (int square) {
    if (width < 0 || height < 0) throw;
    int result = width * height;
    return result;
  }
}
contract DemoTypes {
  /*输入N,计算N的阶乘,循环实现*/
  function f3(uint n) returns (uint jiecheng) {
    if (n == 0) throw; uint result = 1;
    for (uint i=1; i<=n; i++) {
      result *= i;
    }
    return result;
  }
}

 在合约中写测试代码

   区块链技术和以前技术最大的不同就在于开源化,尤其是智能合约部分,必须要开源。因此测试代码就非常重要。

    所以建议大家在撰写智能合约的时候随便把测试代码带上,这个也是成为以太坊开源社区贡献者的必备条件

  

数组类型

  solidity语言中,int/uint数组类型的定义方式如下

  uint[] a;

 int [] b;

数组类型的成员有两个length和push

 push是给数组类型增加一个元素,同时该数组的长度加1

length返回当前数组的长度。有一个元素,则返回1,有两个元素返回2

pragma solidity ^0.4.8;
contract DemoTypes4 {
  uint[] public intArray;
  function add(uint a) {
    intArray.push(a);
  }
}

上面的合约很简单,定义了一个public的int类型数组intArray,以及一个方法add 

String 数组类型定义

 string[] strArr;

String数组的增删改查

pragma solidity 0.4.24;

 contract Demo{

   string[] public srrArr;

   function Deom(){

     srtArr.push("init");

}}

 function add(string str){

    srtArr.push(str);

}

function update(uint index,string str){

 if(index>=strArr.length) throw;

 strArr[index]= str;

}

Enum数据类型定义

 enum ActionCode{Left,Right,Foward,Rollback}

 ActionCode public b2;

Enum Demo代码

  pragma solidity 0.4.24;

  contract Deom{

    enum ActionCode{Left,Right,Foward, Rollback}

    ActionCode public b2;

}

在加一个构造函数的功能,并且给b2赋予一个初始值

 function Demo(){

  b2 = ActionCode.Left;

}

 设置一个判断函数,输出结果

 function f () returns (string str){

  if(b2==ActionCode.Left) return “letf”}

Struct类型定义 :定义struct类型的person

  struct Person{

     string name ;

     uint sexy;

      uint age;

      string mobile;  

}

   建立一个Struct的Demo合约

 pragma solidity 0.4.24;

 contract Demo{

  struct Person{

    string name ;

    uint sexy;

    uint age;

    string mobile;  

 }

  Person[] public Personlist;

}

创建一个构造函数添加初始化代码

  function Demotypes9(){

    uint id = Persionlist.length++;

    Person p = Personlis[id];

    p.name ="啊三";

    p.sexy  = 0 ;

    p.age = 20;

     p.moblie = "13918802350"

   }

    

address类型一般用来保存accounts的公钥信息

 pragma solidity 0.4.24;

  contract Coin{

     address public adc;

    function Coin(){

      abc = msg.sender;

}

   function pay() returns (address n ){

     address  result; 

     result = msg.sender;

      return result ;

}}

  

 }

      

猜你喜欢

转载自blog.csdn.net/qq_36344771/article/details/81078018