Chr*_*ang 5 blockchain ethereum solidity
当创建结构时,我很难为结构初始化一个空数组。
pragma solidity ^0.5.1;
contract Board {
//storage
Post[] posts;
//struct
struct Post {
address author;
string title;
string content;
Comment[] comments;
}
struct Comment {
address author;
string comment;
}
//add-post
function addPost(address _author, string memory _title, string memory _content) public {
posts.push(Post(_author, _title, _content, /* HERE IS THE PROBLEM POINT */));
}
}
Run Code Online (Sandbox Code Playgroud)
我想用空数组(类型:注释)初始化注释(结构成员)。我应该使用哪个代码来解决问题点?
郎:坚固
谢谢。
老实说,我不知道如何解决这个问题。我稍微改变了商店,现在可以了,也许对你有帮助
PS在0.4.25版本中你可以返回所有帖子评论,但在0.5.1中我认为它还不支持默认
pragma solidity ^0.5.1;
contract Board {
//storage
uint256 public postAmount = 0;
mapping(uint256 => Post) public posts;
struct Comment {
address author;
string comment;
}
struct Post {
address author;
string title;
string content;
Comment[] comments;
}
//add-post
function addPost(address _author, string memory _title, string memory _content, string memory _comment) public {
Post storage post = posts[postAmount];
post.author = _author;
post.title = _title;
post.content = _content;
bytes memory tempEmptyString = bytes(_comment);
if (tempEmptyString.length != 0) { // check if comment exists
post.comments.push(Comment({
author: _author,
comment: _comment
}));
postAmount++;
}
}
function getComment(uint256 _postIndex, uint256 _commentIndex) public view returns(string memory) {
Post memory post = posts[_postIndex];
return post.comments[_commentIndex].comment;
}
}
Run Code Online (Sandbox Code Playgroud)