亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在結構上定義的公共屬性無法訪問實現接口

在結構上定義的公共屬性無法訪問實現接口

Go
慕容708150 2022-09-12 17:01:36
有一個接口注釋必須實現才能被包功能訪問。盡管實現接口,然后創建 CommentTest 對象的切片,但將注釋作為項類型,會使 Title 公共屬性未定義。PS:在這種情況下,串焊器工作正常。有沒有辦法讓它在沒有類型斷言的情況下工作?package mainimport "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% accesiblefunc (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)}
查看完整描述

2 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

變量的類型是 ,它是一個接口,因此,它是一組方法。它沒有任何成員變量。rootComment


您可以執行以下幾項操作:


如前所述,使用類型斷言。

將一個 GetTitle() 方法添加到注釋測試,并使用一個單獨的接口:

type titler interface { GetTitle() string }

if t, ok:=root.(titler); ok {

    t.GetTitle()

}


查看完整回答
反對 回復 2022-09-12
?
侃侃無極

TA貢獻2051條經驗 獲得超10個贊

接口僅提供對方法的訪問,而不是字段(它們與隱藏在它們后面的任何東西的字段布局無關,或者它是否甚至是一個結構)。您可以向接口添加一個方法,并使用該方法。GetTitle()



查看完整回答
反對 回復 2022-09-12
  • 2 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號