有一个接口注释必须实现才能被包功能访问。尽管实现接口,然后创建 CommentTest 对象的切片,但将注释作为项类型,会使 Title 公共属性未定义。PS:在这种情况下,串焊器工作正常。有没有办法让它在没有类型断言的情况下工作?
package main
import "fmt"
type Comment interface {
SetChild(Comment)
GetChildren() []Comment
GetID() int
GetParentID() int
}
type CommentTest struct {
Title string
ID int
ParentID int
Children []Comment
}
func (ct *CommentTest) SetChild(c Comment) {
ct.Children = append(ct.Children, c)
}
func (ct CommentTest) GetChildren() []Comment {
return ct.Children
}
func (ct CommentTest) GetID() int {
return ct.ID
}
func (ct CommentTest) GetParentID() int {
return ct.ParentID
}
// works well, all public properties are 100% accesible
func (ct CommentTest) String() string {
return "{ID: " + strconv.Itoa(ct.ID) + ", ParentID: " + strconv.Itoa(ct.ParentID) + ", Title: " + ct.Title + "}"
}
/*
There are test comments with this structure:
1 ->
2 ->
4
3 ->
5
*/
func testData() (Comment, []Comment) {
var plain []Comment
root := &CommentTest{ID: 1, ParentID: 3, Title: "Test 1"} // ParentID 3 -> Check for infinite recursion
plain = append(plain, root)
plain = append(plain, &CommentTest{ID: 2, ParentID: 1, Title: "Test 2"})
plain = append(plain, &CommentTest{ID: 3, ParentID: 1, Title: "Test 3"})
plain = append(plain, &CommentTest{ID: 4, ParentID: 2, Title: "Test 4"})
plain = append(plain, &CommentTest{ID: 5, ParentID: 3, Title: "Test 5"})
return root, plain
}
func main() {
root, plain := testData()
fmt.Println(root) // works well
root.Title //root.Title undefined (type Comment has no field or method Title)
}
守着一只汪
侃侃无极
相关分类