Solidity: Using Arrays in Structs for Contract Development

arrayssoliditystruct

I have a User struct and in it I want to have an array with the users posts.
But every way I tried to add an empty array it threw an error.
So i want to init an empty array but be able to push things to it later.

address payable public Owner;

mapping(address => User) public users;

struct User {
    address useraddress;
    Post[] posts;
}

struct Post {
    string contentlink;
    uint likes;
    uint dislikes;
}

constructor() {
    Owner = payable(msg.sender);
}

function login() public {
    require(users[msg.sender].useraddress != msg.sender, "Already have account");
    users[msg.sender] = User(msg.sender, new Post());
}

Best Answer

I encountered the exact same problem when I was trying to implement a very similar smart contract. Ultimately, I ended up changing my design pattern. Solidity doesn't yet support initialization of a struct array from memory when trying to write to a storage array in a struct. Hopefully this will be supported in the future because it's quite limiting.

My workaround was opting for this design pattern, where the array of structs is declared outside of the struct itself. I then just map each address to that struct array. It's not pretty, but it does work.

address[] internal addresses;
mapping(string => address) internal names;
mapping(address => Profile) public profiles;
mapping(address => mapping(address => Profile)) internal followers;
mapping(address => mapping(address => Profile)) internal following;
mapping(address => Post[]) internal posts;

// Profile
struct Profile {
    address owner;
    string name;
    uint timeCreated;
    uint id;
    uint postCount;
    uint followerCount;
    uint followingCount;
    address[] followers;
    address[] following;
}

// Post
struct Post {
    address author;
    string content;
    uint timeCreated;
    uint id;
}

You can find my full implementation here:

https://gist.github.com/charlesalexanderlee/c97d6169c9d65d03d74bb25a07d442e1

Related Topic