我应该如何将值添加到具有部分参数的结构中

Posted

技术标签:

【中文标题】我应该如何将值添加到具有部分参数的结构中【英文标题】:how should I add values to structures with partial arguments in solidity 【发布时间】:2021-06-29 20:07:49 【问题描述】:
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: Wrong argument count for struct constructor: 1 arguments given but expected 2. clusternodes[_basename].push(ClusterNode(_clustername));

请让我摆脱这个,或者他们是否有任何替代解决方案,请告诉我

【问题讨论】:

【参考方案1】:

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

当您创建实例时,您将传递ClusterNode(_clustername, null )。但是null 在 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
  


【讨论】:

当我尝试这段代码时,我收到了这个错误 UnimplementedFeatureError: Copying of type struct ClusterNode memory[] memory to storage not yet supported. @vijaykumar 该错误是由上述代码以外的其他东西产生的。也许你错误地改变了它?我能够成功编译(在 Solidity 0.8.3 下)并创建一个调用 addClusterNode() 函数的事务。 imgur.com/JQMQ7sK

以上是关于我应该如何将值添加到具有部分参数的结构中的主要内容,如果未能解决你的问题,请参考以下文章

如何将值添加到 Spring Data Redis 中的嵌入集

如何查询行中是不是存在值将值添加到另一个字段?

如何使用 SQL 查询将值传递给具有空间/地理数据类型的存储过程

如何将值从javascript传递到iOS UIWebView

如何将值插入单链表

如何在 JavaScript 中取消移位或添加到参数对象的开头