[Ethereum Development-03] Solidity Basic Grammar (Medium)

The previous issue mainly introduced some data types, and this issue continues to introduce the use of data types in detail

1. Fixed-length byte array

Solidity has some built-in array data types:

  • bytes1 , … , bytes32 , allow values ​​incremented in steps of 1.
  • By default, byte means bytes1, byte is the type, bytes is the type, and bytes1 is the built-in array
  • bytes1 can only store 1 byte, that is, 8-bit content, and bytes2 can only store up to 2 bytes, that is, 16-bit content. And so on...
  • Read length length
  • The length cannot be modified
  • can be accessed by subscripting
  • Content cannot be modified
pragma solidity ^0.4.2;
//bytes1
contract fixedArray {
    
    
 
 /*
 1. ⻓度可以读取 length
 2. ⻓度不可以修改
 3. 可以通过下标访问
 4. 内容不可修改 
 */
 //bytes1 ... bytes32
 
 //bytes1 b1 = "xy";
 bytes2 b2 = "xy";
 
 bytes3 public b3 = "xy";
 
 uint public len = b3.length;
 
 //b3.length = 10;
 
 bytes8 b8 = "12345678";
 
 //b8_0返回0x31,即⼗进制的数字1的ascii值(3*16+1=49)
 bytes1 public b8_0 = b8[0];
 
 //b = "HELLO";ERROR,定义之后不可修改
 //b8[1] = "0";
 //b8= "4567";
}

dynamically sized byte array

bytes : byte array of dynamic length (non-value type)
string : UTF-8 encoded character type of dynamic length (non-value type)

A good usage principle is: bytes are used to store characters of any length section data, and string is used to store UTF-8 encoded
string data of any length. If the length can be determined, try to use a fixed length such as byte1 to byte32, because it saves more space.

bytes dynamic byte array

  • You can directly assign strings regardless of space, and the space will be automatically allocated
  • If no space has been allocated, subscript access will result in an out-of-bounds error
  • The length can be set, the corresponding space is automatically allocated, and it is initialized to 0
  • Data can be modified by subscript
  • Support push operation, append elements at the end of bytes
pragma solidity ^0.4.24;


contract  Test {
    
    

    bytes public name;
    
    
    function getLen() public view returns(uint256) {
    
    
        return name.length;
    }

    //1. 可以不分空间,直接进行字符串赋值,会自动分配空间
    function setValue(bytes input) public {
    
    
        name = input;
    }
    
    //2. 如果未分配过空间,使用下标访问会访问越界报错
    function getByIndex(uint256 i) public view returns(byte) {
    
    
        return name[i];
    }
    
    //3. 可以设置长度,自动分配对应空间,并且初始化为0
    function setLen(uint256 len) public {
    
    
        name.length = len;
    }
    
    
    //4.可以通过下标进行数据修改
    function setValue2(uint256 i) public {
    
    
        name[i] = 'h';
    } 
    
    //5. 支持push操作,在bytes最后面追加元素
    function pushData() public {
    
    
        name.push('h');
    } 
}

string string

  • Dynamically sized UTF-8 encoded strings, which are special mutable byte arrays
  • reference type
  • Subscript indexes are not supported
  • The length and push methods are not supported
  • Can be modified (need to convert bytes)
pragma solidity ^0.4.24;


contract  Test {
    
    

    string public name = "lily";
    
    
    function setName() public {
    
    
        bytes(name)[0] = "L";   
    }
    
    function getLength() public view returns(uint256) {
    
    
        return bytes(name).length;
    }
    
    function setLength(uint256 i) public {
    
    
        bytes(name).length = i;
        
        bytes(name)[i - 1] = 'H';
    } 
}

3. Conversion (byte1/bytes/string)

insert image description here

pragma solidity ^0.4.24;
contract Test {
    
    
 
 bytes10 b10 = 0x68656c6c6f776f726c64; //helloworld
 //bytes bs10 = b10; //⽆法直接转换
 
 
 bytes public bs10 = new bytes(b10.length);
 
 //1. 固定字节数组转动态字节数组
 function fixedBytesToBytes() public{
    
    
 for (uint i = 0; i< b10.length; i++){
    
    
 bs10[i] = b10[i];
 }
 }
 
 //2.string转动态字节数组
 string greeting = "helloworld";
 bytes public b1;
 function StringToBytes() public {
    
    
 b1 = bytes(greeting);
 }
 
 //3. 动态字节数组转string
 string public str3;
 function BytesToString() public {
    
    
 fixedBytesToBytes();
 str3 = string(bs10);
 }
 //4. fixed bytes to String,error
 function FiexBytesToString(){
    
    
 //string tmp = string(b10);
 }
}

4. Array

built-in arrays (introduced)

  • string (variable length)
  • bytes (variable length)
  • bytes1…bytes32 (fixed length)

custom array

Custom fixed-length array

  • An array of type T and length K is defined as T[K], for example: uint [5] numbers, byte [10] names;
  • variable content
  • The length is immutable and does not support push
  • Support length method
pragma solidity ^0.4.5;
contract test {
    
    
 
 //test1:
 uint[10] value = [1,2,3,4,5];
 uint public sum;
 function getSum(){
    
    
 sum = 0;
 for (uint i = 0; i < value.length; i++){
    
    
 sum += value[i];
 } 
 }
 
 function changeValue(){
    
    
 value[0] = 2; //内容可修改
 //value.length = 100; //报错,⻓度不可修改
 }
 }

variable length array

  • The definition format is T [ ], for example: string[ ] names, byte[ ] cities.
  • content can be modified
  • The length can be changed (storage type only) and length and push methods are supported
  • Variable-length arrays of memory type do not support length modification
pragma solidity ^0.4.24;


contract  Test {
    
    
    
    //第一种创建方式,直接赋值
    uint8[] numbers = [1,2,3,4,5,6,7,8,9,10];
    
    function pushData(uint8 num) public {
    
    
        numbers.push(num);
    }
    
    function getNumbers() public view returns(uint8[]) {
    
    
        return numbers;
    }
    
    
    //使用new关键字进行创建,赋值给storage变量数组
    uint8[] numbers2;
    
    function setNumbers2() public {
    
    
        numbers2 = new uint8[](7);
        numbers2.length = 20;
        numbers2.push(10);
    }
    
    function getNumbers2() public view returns(uint8[]) {
    
    
        return numbers2;
    }
    
    function setNumbers3() public {
    
    
        //使用new创建的memory类型数组,无法改变长度
        //uint8[] memory numbers3 = new uint8[](7);
        uint8[] memory numbers3;
        
        //numbers3.push(10);     
    }
}

5. Structure

pragma solidity ^0.4.5;
contract Test {
    
    
 //定义结构之后⽆分号,与枚举⼀致
 struct Student {
    
    
 string name;
 uint age;
 uint score;
 string sex;
 }
 Student[] public Students;
 
 
 //两种赋值⽅式
 Student public stu1 = Student("lily", 18, 90, "girl");
 Student public stu2 = Student({
    
    name:"Jim", age:20, score:80,
sex:"boy"});
 
 function assign() public {
    
    
 Students.push(stu1);
 Students.push(stu2);
 
 stu1.name = "Lily";
 }
}

6. Dictionary/mapping/hash table (mapping)

  • The key type allows all types except mapping, such as arrays, contracts, enumerations, structures, and the value type is unlimited.
  • Mapping cannot be traversed, and it is impossible to judge whether a mapping contains a certain key, because it thinks that each key exists, and returns 0 or false if it does not exist.
  • The mapping can be regarded as a hash table. In the mapping table, the data of the key is not stored, but only its keccak256 hash value is stored, which is used when looking up the value.
  • Mapping types can only be used to define state variables, and cannot be used as parameters and return values ​​of shared functions.
  • length is not supported
  • Mappings declared as public will automatically create a getter function with the key as the parameter and the value as the return value.
pragma solidity ^0.4.20;


contract Test {
    
    
    //id -> name
    mapping(uint => string) public id_names;
    
    
    
    //构造函数:
    //1. 对象在创建的时候,自动执行的函数,完成对象的初始化工作
    //2. 构造函数仅执行一次
    
    // function Test() public {
    
    
        
    // }

    constructor()  public{
    
    
        id_names[1] = "lily";
        id_names[2] = "Jim";
        id_names[3] = "Lily";
        id_names[3] = "Tom";
    }
    
    function getNameById(uint id)  public returns (string){
    
    
        //加上storage如何赋值?
        string memory name = id_names[id];
        return name;
    }
    
    function setNameById(uint id)  public returns (string){
    
    
        // mapping(uint => string) memory id_name = id_names;
        // var ids = id_names;
        id_names[id] = "Hello";
    }
    
    
    // function getMapLength() public returns (uint){
    
    
    //     return id_names.length;
    // }
    
}

Guess you like

Origin blog.csdn.net/weixin_42918559/article/details/125083011