首页 > 解决方案 > 我应该如何为具有部分参数的结构添加值

问题描述

contract ClusterHeadNode {

  struct ClusterNode {
      
      string name;
      string[] ordinarynodes;
  }
  mapping(string => ClusterNode[]) clusternodes;

  
  mapping(string => string[]) headnodes;

  function addClusterNode(string memory  _basename , string memory _clustername) internal {
      
        clusternodes[_basename].push(ClusterNode(_clustername, null ));
        
    }
    
    function getClusterNodes(string memory _name) public view returns(string[] memory){
        return headnodes[_name];
    }

}

在上面的代码中,我应该在 clusterNode 结构中添加唯一的名称

在尝试这个时我遇到了一个错误

** contracts/hybridblockchain.sol:19:38:TypeError:结构构造函数的参数计数错误:1 个参数给出但预期 2.clusternodes[_basename].push(ClusterNode(_clustername));

请让我摆脱这种情况,或者他们是否有任何替代解决方案请告知

标签: blockchainethereumsoliditysmartcontractsweb3js

解决方案


您的结构包含两种类型:stringstring[](字符串数组)。

当您创建实例时,您正在传递ClusterNode(_clustername, null ). Butnull不是 Solidity 中的有效值,编译器会忽略它(不是因为它无效,而是因为它为 null)。

解决方案:传递一个空数组

我根据您的原始代码制作了一个传递空数组的缩小示例:

pragma solidity ^0.8.0;

contract ClusterHeadNode {

  struct ClusterNode {
      string name;
      string[] ordinarynodes;
  }

  mapping(string => ClusterNode[]) clusternodes;

  function addClusterNode(string memory _basename, string memory _clustername) external {
      string[] memory ordinarynodes;  // instanciate empty array
      ClusterNode memory clusternode = ClusterNode(_clustername, ordinarynodes); // instanciate the struct, pass the empty array to the struct
      clusternodes[_basename].push(clusternode); // push the struct into the array of structs
  }

}

推荐阅读