如何在stuct [Solidity]

时间:2018-12-05 10:31:45

标签: 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 */));
    }
}

我想用Empty Array(类型:Comment)初始化注释(结构成员)。 我应该为问题点使用哪个代码?

郎:坚强

谢谢。

1 个答案:

答案 0 :(得分:1)

老实说,我不知道如何解决这个问题。我稍微改变了商店,现在可以了,也许对您有帮助

P.s为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;
    }
}