Blockchain 如何在stuct[Solidity]中初始化空数组
当创建结构时,我正在为结构初始化一个空数组Blockchain 如何在stuct[Solidity]中初始化空数组,blockchain,ethereum,solidity,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 Comme
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 */));
}
}
我想用空数组(类型:Comment)初始化注释(结构成员)。
对于问题点,我应该使用哪种代码
朗:坚固
谢谢。老实说,我不知道如何解决这个问题。我改变了一点商店,现在它工作了,也许它会对你有帮助 另外,在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;
}
}
谢谢你,你的回答给我留下了深刻的印象。如果没有初始注释,该如何处理?在我的代码中,如果没有初始注释,注释是可选的,它将只创建帖子,而不推入注释数组或使用空数组(如果还没有注释)