在结构上定义的公共属性无法访问实现接口

有一个接口注释必须实现才能被包功能访问。尽管实现接口,然后创建 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)


}


慕容708150
浏览 115回答 2
2回答

守着一只汪

变量的类型是 ,它是一个接口,因此,它是一组方法。它没有任何成员变量。rootComment您可以执行以下几项操作:如前所述,使用类型断言。将一个 GetTitle() 方法添加到注释测试,并使用一个单独的接口:type titler interface { GetTitle() string }if t, ok:=root.(titler); ok {    t.GetTitle()}

侃侃无极

接口仅提供对方法的访问,而不是字段(它们与隐藏在它们后面的任何东西的字段布局无关,或者它是否甚至是一个结构)。您可以向接口添加一个方法,并使用该方法。GetTitle()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go