有一個接口注釋必須實現才能被包功能訪問。盡管實現接口,然后創建 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()
}

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
接口僅提供對方法的訪問,而不是字段(它們與隱藏在它們后面的任何東西的字段布局無關,或者它是否甚至是一個結構)。您可以向接口添加一個方法,并使用該方法。GetTitle()
- 2 回答
- 0 關注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消