Solidity

是否可以在映射內部進行映射?

  • November 15, 2018

這可能嗎?

mapping(address => mapping(uint => customStruct[])) someName

因為我無法調試並發現我的錯誤……是否沒有足夠的氣體,或者它在嘗試填充時在此程式碼上崩潰someName

例如:

uint length = someName[msg.sender][1].length;
someName[msg.sender][1][length].timestamp = block.timestamp;

我想 customStruct 是一個帶有時間戳屬性的結構。然後你的程式碼應該可以工作。但是這裡我的測試場景:

import "dapple/test.sol";


contract MyTest is Test {

 struct Struct {
   uint timestamp;
 }

 // Mapping test
 mapping(uint => mapping(uint => uint)) mymap;

 mapping(address => mapping(uint => Struct[])) someName;

 function testNestedMappings() {
   //@log test nested mappings
   mymap[1][2] = 42;
   //@log mymap[1][2] = `uint mymap[1][2]`
   //@log test struct array:
   //@log someName[msg.sender][1].length = `uint someName[msg.sender][1].length`
   //@log incrementing length
   someName[msg.sender][1].length++;
   //@log saving timestamp to last entry
   someName[msg.sender][1][someName[msg.sender][1].length - 1].timestamp = block.timestamp;
   //@log `uint someName[msg.sender][1][someName[msg.sender][1].length-1].timestamp`
 }
}

執行時dapple test --report輸出以下內容:

MyTest
 test nested mappings
 LOG:  test nested mappings
 LOG:  mymap[1][2] = 42
 LOG:  test struct array:
 LOG:  someName[msg.sender][1].length = 0
 LOG:  incrementing length
 LOG:  saving timestamp to last entry
 LOG:  1460035092
 Passed!

因為我無法調試

…但這很重要

引用自:https://ethereum.stackexchange.com/questions/2718