将元素添加到struct

时间:2017-03-14 12:56:03

标签: solidity smartcontracts

我不能使用(推送),因为它仅与状态变量一起使用

这是错误:

Error message

(推)是否有其他选择

  contract m{


  struct Message{

    address sender;
    address receiver;
    uint msgContent;

                } // end struct

 Message[] all; 

function get ( address from ) internal 
                                        returns ( Message[] subMsgs){


     for ( uint i=0; i<all.length ; i++)

      {
         if ( all[i].sender == from )
             { 
               subMsgs.push (all[i]);
             }
      }


          return subMsgs;  
          } 
       } // end contract 

1 个答案:

答案 0 :(得分:2)

您只能在动态大小的数组(即存储阵列)上使用push,而不能使用固定大小的数组(即内存数组)(有关详细信息,请参阅Solidity array documentation)。

为了达到你想要的效果,你需要创建一个具有所需大小的内存数组,并逐个分配每个元素。以下是示例代码:

contract m {

    struct Message{
        address sender;
        address receiver;   
        uint msgContent;            
    } // end struct

    Message[] all;

    function get(address from) internal returns (Message[]) {

        // Note: this might create an array that has more elements than needed
        // if you want to optimize this, you'll need to loop through the `all` array
        // to find out how many elements from the sender, and then construct the subMsg
        // with the correct size
        Message[] memory subMsgs = new Message[](all.length);
        uint count = 0;
        for (uint i=0; i<all.length ; i++)
        {
            if (all[i].sender == from)
            {
                subMsgs[count] = all[i];
                count++;
            }
        }
        return subMsgs; 
    }
} // end contract