无法构造包含(嵌套)映射的结构。坚固
Struct containing a (nested) mapping cannot be constructed. in solidity
我用的是solidity版本pragma solidity 0.8.6;
我有一个这样的结构:
struct Request {
string description;
uint256 value;
address recipient;
bool complete;
uint256 approvalCount;
mapping(address => bool) approvals;
}
当我需要为该结构创建实例时,它会向我显示此错误:
Struct containing a (nested) mapping cannot be constructed
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
它在我需要传输时显示此错误:
request.recipient.transfer(request.value);
"send" and "transfer" are only available for objects of type "address payable", not "address".
有什么问题吗?我该如何解决这个问题?
这是故意限制。参见 Disallow mappings in memory and copying mappings. The problem is that mappings are only allowed in storage due to their layout and cannot really be copied together with the struct (see my answer for "How to return an array of structs that has mappings nested within them?")。
过去可以在 memory
中创建包含映射的结构,但这只会使映射留空。这种静默行为很容易导致错误,从 0.8.0 开始,它被明确禁止。
您的解决方案取决于您要完成的具体目标。要么创建一个没有映射字段的单独结构以在内存中使用,要么更好的是,完全避免将其复制到内存中。
您可以使 newRequest
成为一个存储变量,并在您发出新请求时覆盖它。您也可以将类型更改为 Request[]
并在创建新类型时使用 push()
以保留旧类型。
从 Solidity v0.7.0 开始更改(不安全的功能)
如果存储中包含映射,则对结构或数组的赋值将不起作用。以前,映射在复制过程中被静默跳过
误导和容易出错的操作。
请参阅 v0.7.0 重大更改:
https://docs.soliditylang.org/en/v0.8.9/070-breaking-changes.html
编辑:解决方案:首先将结构实例添加到存储
我用的是solidity版本pragma solidity 0.8.6;
我有一个这样的结构:
struct Request {
string description;
uint256 value;
address recipient;
bool complete;
uint256 approvalCount;
mapping(address => bool) approvals;
}
当我需要为该结构创建实例时,它会向我显示此错误:
Struct containing a (nested) mapping cannot be constructed
Request memory newRequest = Request({
description: description,
value: value,
recipient: recipient,
complete: false,
approvalCount: 0
});
它在我需要传输时显示此错误:
request.recipient.transfer(request.value);
"send" and "transfer" are only available for objects of type "address payable", not "address".
有什么问题吗?我该如何解决这个问题?
这是故意限制。参见 Disallow mappings in memory and copying mappings. The problem is that mappings are only allowed in storage due to their layout and cannot really be copied together with the struct (see my answer for "How to return an array of structs that has mappings nested within them?")。
过去可以在 memory
中创建包含映射的结构,但这只会使映射留空。这种静默行为很容易导致错误,从 0.8.0 开始,它被明确禁止。
您的解决方案取决于您要完成的具体目标。要么创建一个没有映射字段的单独结构以在内存中使用,要么更好的是,完全避免将其复制到内存中。
您可以使 newRequest
成为一个存储变量,并在您发出新请求时覆盖它。您也可以将类型更改为 Request[]
并在创建新类型时使用 push()
以保留旧类型。
从 Solidity v0.7.0 开始更改(不安全的功能)
如果存储中包含映射,则对结构或数组的赋值将不起作用。以前,映射在复制过程中被静默跳过 误导和容易出错的操作。
请参阅 v0.7.0 重大更改: https://docs.soliditylang.org/en/v0.8.9/070-breaking-changes.html
编辑:解决方案:首先将结构实例添加到存储