Solidity first assignment

Table of contents

first question

Complete the following code exercises

second question

Look at the code first

answer the questions


first question

Complete the following code exercises

Please write a simple smart contract set and get, and use the last two digits of your student number as the code set get. It means set your own student number (the last two digits) and get your own student number (the last two digits).

// SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;

contract Test1 {
    uint8 id;
    
    function set(uint8 _id) public {
        id = _id;
    }
     
    function get() public view returns(uint8){
        return id;
    }
} 

second question

Look at the code first

// SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;

contract Test1 {

    string names = 'lyk';
    string name = unicode'罗永康';
    
    function change(string memory _name) public {
        name = _name;
    }
     
    function get() public view returns(string memory){
        return name;
    }
    
    function f(int _a) public pure returns(int){
        _a++;
        return _a;
    }

answer the questions

1. And talk about what should be paid attention to in string assignment and definition?

2. Talk about which of the above functions will consume gas, which functions will not consume gas, and why?

3. What is the difference between pure and view modified functions?

answer:

1. The string is a reference data type. When used as a function parameter (input parameter and output parameter), it needs to be specified in memory

When the character string is assigned as a Chinese character, unicode needs to be used for transcoding, because ASCII cannot represent Chinese characters. A Chinese character is equal to 3 bytes

2. The above change function will consume gas, because the state variable name is modified, and the pure and view modifiers cannot be used. The get function and the f function will not consume gas because the pure and view modifiers are used

3. The function modified by pure does not read or modify the state variables, and the view only reads the state variables and does not modify the state variables. Functions modified by pure and view do not consume gas

Guess you like

Origin blog.csdn.net/weixin_62421736/article/details/131067294