如何理解合约中的引用类型(4)——String和Bytes

常用的知识点都在注释里表达了

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;

contract BytesAndString {
    
    
    //初始化方式 new
    string name =  "BytesAndString"; //new string(5);
    bytes name1 = "BytesAndString1"; //new bytes(5);
    // string是不能修改的(强转为bytes后可以改),bytes可以修改
    // string name2 = new string(5); // 因此这样赋值没有意义

    function testStringAndBytes()public view returns(string memory){
    
    
        string memory data = "xyz";//new string(5);
        bytes memory data1 = "abc";//new bytes(5);
        

        //不同location的memory拷贝
        data = name;
        data1 = name1;

        // 类型转换
        data1 = bytes(data);
        data = string(data1);

        // 下标访问
        // bytes1 b = data[0];
        // data[0] = 0x88;
        // bytes1 b = data1[0]; 
        data1[0] = 0x88;

        // 能够push pop吗?types可以,string不行,因为string不可修改嘛
        // name1.push(0x00);
        // data1.push(0x00);
        return data;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37117521/article/details/139155204