Solidity
結構中的數組
我有一個使用者結構,我想在其中有一個包含使用者文章的數組。但是我嘗試添加一個空數組的每一種方式都會引發錯誤。所以我想初始化一個空數組,但以後可以把東西推到它上面。
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()); }
當我嘗試實現一個非常相似的智能合約時,我遇到了完全相同的問題。最終,我最終改變了我的設計模式。當嘗試寫入結構中的儲存數組時,Solidity 還不支持從記憶體初始化結構數組。希望這將在未來得到支持,因為它非常有限。
我的解決方法是選擇這種設計模式,其中結構數組在結構本身之外聲明。然後我將每個地址映射到該結構數組。它不漂亮,但它確實有效。
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; }
你可以在這裡找到我的完整實現:
https://gist.github.com/charlesalexanderlee/c97d6169c9d65d03d74bb25a07d442e1