0

我不能使用( push ),因为它只与状态变量一起使用

这是错误:

错误信息

(推)有没有其他选择

  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 
4

1 回答 1

2

您只能用于push动态大小的数组(即存储数组),而不是固定大小的数组(即内存数组)(有关更多信息,请参阅Solidity 数组文档)。

因此,要实现您想要的,您需要创建一个具有所需大小的内存数组并一个一个地分配每个元素。这是示例代码:

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
于 2017-03-23T06:24:40.290 回答