Solidity

我可以將結構保存在映射中嗎?

  • June 17, 2021

是否可以將結構儲存在我的 Solidity SmartContract 中的映射或任何動態記憶體結構中?

您可以將結構儲存為映射的值,而不是鍵。以下是更多資訊:http ://solidity.readthedocs.org/en/latest/types.html#structs

struct Funder {
 address addr;
 uint amount;
}

struct Campaign {
 address beneficiary;
 uint fundingGoal;
 uint numFunders;
 uint amount;
 mapping (uint => Funder) funders;
}

uint numCampaigns;
mapping (uint => Campaign) campaigns;

是的你可以。

例如,在下面的solidity 程式碼中。有一個 structUser具有friends從 , fromaddress到另一個 struct的映射Friend

然後是使用者的映射,從addressUser[注意這User是一個結構]。

struct Friend {
   string name;
   string email;
   string phoneNumber;
}

struct User {
   string name;
   string email;
   uint256 balance;
   mapping (address => Friend) friends;
}

mapping (address => User) public users;

因此,假設使用者 A 有朋友 B、C 和 D。User可以想像如下:

{
   name: 'A',
   email: [email],
   balance: [balance],
   friends: {
       [address_of_friend_B]: {
           name: 'B',
           email: [email],
           phoneNumber: [phoneNumber],
       },
       [address_of_friend_C]: {
           name: 'C',
           email: [email],
           phoneNumber: [phoneNumber],
       },
       [address_of_friend_D]: {
           name: 'D',
           email: [email],
           phoneNumber: [phoneNumber],
       },
   }
}

如果有很多這樣User的結構,比如 A、J、Z、…,映射users包含它們:

{
   name: 'A',
   ...
   friends: {...},

   name: 'J',
   ...
   friends: {...},

   name: 'Z',
   ...
   friends: {...},
}

所以是的,您可以將結構儲存在映射中。

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