繁体   English   中英

以实体形式返回数组或对象列表

[英]return array or list of objects in solidity

我是 Solidity 的新手,正在尝试对我在 Inte.net 上找到的代码进行一些修改。 下面给出的是 V.NET 合约:

contract VANET {
    string name;
    string owner;
    string number;
    string license;
    event Vehicle(
        string name,
        string owner,
        string number,
        string license
    );
    function setVehicle(string _name, string _owner, string _number, string _license) public{
        name=_name;
        owner=_owner;
        number=_number;
        license=_license;
        Vehicle(_name, _owner, _number, _license);
    }
    function getVehicle() public constant returns (string, string, string, string){
        return (name, owner, number, license);
    }

当我尝试使用以下代码调用 getVehicle() 时:

 VANET.methods.getVehicle().call().then(r=>{
        console.log(r);  //outputs only the last vehicle added
      })

它只显示最后添加的车辆。 我想要的是使用 setVehicle() function 添加到区块链的所有车辆的列表。我该怎么做?

每次调用setVehicle()时,它都会重写存储属性的值。

因此,最直接的方法是将所有这些值分组到一个struct (类对象类型)中,然后将这些结构放在一个数组中,这样您就可以保留所有输入值。 然后你可以简单地检索整个数组:

pragma solidity ^0.8;

contract VANET {
    struct Vehicle {
        string name;
        string owner;
        string number;
        string license;
    }
    Vehicle[] private vehicles;

    event VehicleAdded(
        string name,
        string owner,
        string number,
        string license
    );

    function addVehicle(string memory _name, string memory _owner, string memory _number, string memory _license) public {
        vehicles.push(
            Vehicle(_name, _owner, _number, _license)
        );
        emit VehicleAdded(_name, _owner, _number, _license);
    }

    function getVehicles() public view returns (Vehicle[] memory) {
        return vehicles;
    }
}

看来您的代码片段使用的是已弃用的 Solidity 版本(我猜是 0.4),而我使用最新版本 0.8 编写了示例。 这些版本之间有一些细微的语法变化,所以请记住这一点。

你的 solidity 代码只接受 Vehicle 的一个输入。 要保留所有添加的车辆的列表,您可以将它们添加到数组中。

这是一个(尽管很粗糙)示例。

contract VANET {
Vehicle[] vehicles;

struct Vehicle{
    string name;
    string owner; 
    string number; 
    string license;
}

event VehicleEvent(
    string name,
    string owner,
    string number,
    string license
);

function setVehicle(string memory _name, string memory _owner, string memory _number, string memory _license) public{
    vehicles.push(Vehicle(_name, _owner, _number, _license));
    emit VehicleEvent(_name, _owner, _number, _license);
}

function getVehicle(uint256 id) public view returns (string memory name, string memory owner, string memory number, string memory license) {
    return (vehicles[id].name, vehicles[id].owner, vehicles[id].number, vehicles[id].license);
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM