我使用的版本是0.5.2
我正在混音IDE中执行以下代码
pragma solidity ^0.5.2;
contract Lottery {
address public manager;
address payable[] public players;
constructor () public {
manager = msg.sender;
}
function enter() public payable {
require(msg.value > 0.01 ether);
players.push(msg.sender);
}
// function getPlayers() public view returns(address[] memory) {
// return players;
// }
function random() public view returns(uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, now, players)));
}
function pickWinner() public {
uint index = random() % players.length;
players[index].transfer(address(this).balance);
players = new address[](0); // This line of code giving an error
}
}
我得到的错误是:
Type address[] memory is not implicitly convertible to expected type address payable[] storage ref.
在函数 pickWinner():
function pickWinner() public {
uint index = random() % players.length;
players[index].transfer(address(this).balance);
players = new address[](0); // This line of code giving an error
}
我正在尝试将玩家的数组全部重置为 0,以便重置我的彩票合同
可能最好/最简单的做法是players.length = 0
。
请注意,这将使用与数组中元素数量成比例的 gas(因为它会删除所有元素)。如果这是一个问题,您可能需要考虑使用具有单独存储长度的映射。例如
mapping(uint256 => address payable) players;
uint256 playersLength;
然后只需执行playersLength = 0
即可"重置"。
编辑
根据评论,听起来您没有看到基于数组大小的gas使用情况。以下是在混音中进行测试的简单方法:
pragma solidity 0.5.2;
contract Test {
uint256[] foo;
uint256[] bar;
constructor() public {
for (uint256 i = 0; i < 5; i++) {
foo.push(i);
}
for (uint256 i = 0; i < 100; i++) {
bar.push(i);
}
}
function deleteFoo() external {
foo.length = 0;
}
function deleteBar() external {
bar.length = 0;
}
}
在我的测试中,使用 JavaScript VM,deleteFoo
消耗 26,070 gas,deleteBar
消耗 266,267 gas。
function pickWinner() public {
uint index = random() % players.length;
players[index].transfer(address(this).balance);
players = new address payable [](0); //add payable to this line
}