blockchain - 我应该如何为具有部分参数的结构添加值
问题描述
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));
请让我摆脱这种情况,或者他们是否有任何替代解决方案请告知
解决方案
您的结构包含两种类型:string
和string[]
(字符串数组)。
当您创建实例时,您正在传递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
}
}
推荐阅读
- pytest - Pytest:将多个参数传递给夹具
- r - Global Moran's I in R 使用 spdep 包
- python-3.x - Tkinter 条件格式:如果先前的值不相等,则更改颜色?
- java - 如何在spring boot中发送多个requestparams
- c - 使用 SPI for Postgres 时如何拆分记录(用于扩展)
- node.js - BEP-20 代币交易中被低估的交易
- flutter - 我将我的 shell 切换为 fish 并且我的颤动命令被破坏了。我该如何解决?
- java - onRequestPermissionsResult 在 Android Fragment 中已弃用
- categories - 父类别
- ansible - 剧本不返回任何值