簡體   English   中英

我怎樣才能從嵌套數組中檢索結構?

[英]How can I retrieve struct from nested array in solidity?

我想從嵌套的gameBoard數組中獲取User ,以便將其移動到xy的新索引集。 Remix IDE引發此錯誤: TypeError: type struct Game.User storage ref[] storage ref is not implicitly convertible to expected type struct Game.User memory 我最初是在沒有memory情況下嘗試此操作,但這不僅違背了不永久存儲(如果我正確理解的話)的目標,而且還引發了較少有用的錯誤。 請幫忙!

pragma solidity ^0.4.0;

contract Game {
    struct User{
        address owner;
        uint currency;
        uint left;
        uint right;
        uint top;
        uint bottom;
    }
    User[][10][10] public gameBoard;

    function addUser (uint _x, uint _y) public {
        gameBoard[_x][_y].push(User(msg.sender, 10, 5, 5, 5, 5));
    }

    function moveUser (uint _fromX, uint _fromY, uint _toX, uint _toY) public {
        User memory mover = gameBoard[_fromX][_fromY];
        if (mover.owner != msg.sender)return;

        // once I have 'mover', I will check whether
        // I want its the msg.senders and then place
        // it where I want it to go
    }

}

簡短的答案:您索引數組錯誤,並且需要另一組[括號]。

因此,您創建了一個稱為“游戲板”的3維用戶數組。 添加用戶時,將結構正確推入數組的動態第3維。 但是,當您訪問這些結構時,您僅給出兩個維度,因此Solidity返回動態用戶數組。 由於您嘗試將其存儲到結構而不是結構數組中,因此會引發錯誤。 解決該問題的最簡單方法是使用:

User memory mover = gameBoard[_fromX][_fromY][0];

但是,這只會使第一個用戶返回游戲板上的該位置,因此您可能需要進行某種循環(這在合同中並不理想)。 就我個人而言,我更喜歡在使用Solidity時避免使用多維數組,並且說實話,一般來說,所有數組都應使用(盡管它們有其用途)。 映射通常更容易使用,尤其是在處理地址時。 如果有更好的實現方法,您能否詳細說明您正在嘗試做的事情?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM