Is it possible to store structs in a Mapping or any dynamic memory structure in my Solidity SmartContract?
3 Answers
You can store structs as the values of your mapping, not as the key. Here is some more info: 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;
Yes, you can.
For example, in the solidity code below. There is a struct User
that has a mapping of friends
, from address
to another struct Friend
.
Then there's a mapping of users, from address
to User
[note that User
is a struct].
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;
So, say a user A has friends B, C, and D. The User
can be imagined to look like this:
{
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],
},
}
}
And if there are many such User
structs, say A, J, Z, ..., the mapping users
holds them all:
{
name: 'A',
...
friends: {...},
name: 'J',
...
friends: {...},
name: 'Z',
...
friends: {...},
}
So yes, you can store structs in a mapping.
yes, you can use struct in map like this:
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract MyFriends{
struct Friends{
string name;
string[] girlfriends;
bool isSingle;
}
mapping(uint=>Friends) FriendsInfo;
}
wrong codes:
mapping(Friends=>uint) FriendsInfo;