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.
You can find my full implementation here:
https://gist.github.com/charlesalexanderlee/c97d6169c9d65d03d74bb25a07d442e1