Solidity
類型 uint256 不能隱式轉換為預期的類型地址
我的目標是返回映射中的所有家庭成員,但我不斷從混音中得到這個錯誤
Type uint256 is not implicitly convertible to expected type address. --> members[i] = familyMembers[i];
pragma solidity ^0.8.0; contract Family{ mapping(address => uint) public familyMembers; function getAllMembers() public pure returns (address[] memory){ uint addressRegistryCount = 0; address[] memory members= new address[](addressRegistryCount); for (uint i = 0; i < addressRegistryCount; i++) { members[i] = familyMembers[i]; } return members; }
映射是不可迭代的。
為了訪問映射中的插槽之一,您需要使用密鑰。在你的情況下,它是地址。
正確的語法是:
mapping(address => uint) public familyMembers; familyMembers[someAddress] //This will return the number of family members
pragma solidity ^0.8.14; import "hardhat/console.sol"; contract Family { mapping (address => string) public familyMembers; // store data mapping (address => bool) public isInMap; // need this as we can't distinguish a zero cause not in the map from is in map but is zero address[] public keys; // something we can enumerate and use each element as the key for the familyMembers map constructor () { addFamilyMember(address(0x1), "alice"); addFamilyMember(address(0x2), "bob"); addFamilyMember(address(0x3), "cam"); addFamilyMember(address(0x4), "doris"); addFamilyMember(address(0x5), ""); // <--- addFamilyMember(address(0x5), "eve"); // <--- addFamilyMember(address(0x6), "fud"); // <--- addFamilyMember(address(0x6), "fred"); // <--- iterateFamilyMembers(); } function addFamilyMember(address _addr, string memory _name) public { familyMembers[_addr] = _name; if(!isInMap[_addr]) { isInMap[_addr] = true; keys.push(_addr); } } function iterateFamilyMembers() public view { for(uint i; i < keys.length; ++i){ console.log("address: %s, name: %s", keys[i], familyMembers[keys[i]]); } } }
輸出:
console.log: address: 0x0000000000000000000000000000000000000001, name: alice address: 0x0000000000000000000000000000000000000002, name: bob address: 0x0000000000000000000000000000000000000003, name: cam address: 0x0000000000000000000000000000000000000004, name: doris address: 0x0000000000000000000000000000000000000005, name: eve address: 0x0000000000000000000000000000000000000006, name: fred
這是可迭代映射的模式。我們需要一個數組來補充映射,因為它是可迭代的。我們還將每個地圖元素的地址放入數組中,這樣我們就可以在迭代數組時將其用作從地圖中提取值的鍵。
我們還需要另一個地圖來告訴我們是否已經添加了一個元素。我們需要它,因為在solidity中沒有null,所以在某些情況下,我們無法確定從映射返回的零或空字元串是因為它沒有找到,還是被發現並且零或空字元串是一個有效值。
在您的 familyMember / name 範例中,也許這不是問題,但在其他情況下會。
一個問題的例子是地址和賬戶餘額的映射。零餘額是有效且常見的。當我們在映射中查找地址並得到零時,那裡的地址是零餘額還是不存在?我們需要知道這一點才能知道是否向數組中添加另一個元素。
如果我們不想使映射可迭代,那麼為什麼我們得到一個零或一個空字元串可能並不重要。