为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号