Solidity

如何初始化函式內部結構的映射?

  • June 15, 2022

我有一個有地圖的結構,我想動態更新地圖……

程式碼 :

struct task {
       string description;
       status taskStatus;
       address assignedTo;
       uint deadline;
       mapping (address => bool) allocation;
   }
 

function setTask (string memory _desc , address[] calldata _copartner , uint _deadline) external  {
     
      
       TaskList.push(task({description : _desc , taskStatus : status.Set , assignedTo : msg.sender , deadline : block.timestamp + _deadline }));
}

您可以在 structs 數組中創建一個空的 struct 元素,然後您可以通過以下方式用相對值填充它:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Test {

   enum status { Set, Done }
   task[] TaskList;

   struct task {
       string description;
       status taskStatus;
       address assignedTo;
       uint deadline;
       mapping (address => bool) allocation;
   }
   

   function setTask (string memory _desc , address[] calldata _copartner , uint _deadline) external  {
       task storage t = TaskList.push();
       t.description = _desc;
       t.taskStatus = status.Set;
       t.assignedTo = msg.sender;
       t.deadline = block.timestamp + _deadline;
       t.allocation[msg.sender] = true;
   }
} 

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