Solidity 练习:结构体

2022-12-29 Web3 Solidity

# 一、题目说明

结构体允许将数据分组在一起。

# 二、任务列表

  1. 完成函数 get(uint _index)。该函数从数组 cars 中检索存储在 _index 处的 Car 结构体,然后返回存储在结构体中的值。
  2. 完成函数 transfer(uint _index、address _owner)。该函数用于将 cars 数组中存储在 _index 的汽车的 owner 转移给新的 owner。

# 三、解答代码

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

contract StructExamples {
    struct Car {
        string model;
        uint year;
        address owner;
    }

    Car[] public cars;

    function examples() external {
        // 3 ways to initialize a struct
        Car memory toyota = Car("Toyota", 1980, msg.sender);
        Car memory lambo = Car({
            model: "Lamborghini",
            year: 1999,
            owner: msg.sender
        });
        Car memory tesla;
        tesla.model = "Tesla";
        tesla.year = 2020;
        tesla.owner = msg.sender;

        // Push to array
        cars.push(toyota);
        cars.push(lambo);
        cars.push(tesla);
        // Initialize and push in single line of code
        cars.push(Car("Ferrari", 2000, msg.sender));

        // Get reference to Car struct stored in the array cars at index 0
        Car storage car = cars[0];
        // Update
        car.year = 1988;
    }

    function register(string memory _model, uint _year) external {
        cars.push(Car({model: _model, year: _year, owner: msg.sender}));
    }

    function get(uint _index)
        external
        view
        returns (
            string memory model,
            uint year,
            address owner
        )
    {
        Car storage car = cars[_index];
        return (car.model, car.year, car.owner);
    }

    function transfer(uint _index, address _owner) external {
        cars[_index].owner = _owner;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

# 四、参考资料

Last Updated: 2023-01-28 4:31:25