dongxie3701 2013-01-23 21:28
浏览 28

了解界面

I am a newbie in Go lang , I was trying to understand Go Interface by writing a simple piece of code . I am getting an error , as I am not able to understand the correct way of referring to a Interface method kindly tell me where I am going wrong.

type Info interface {
Noofchar() int
}

type Testinfo struct {
noofchar int
}

func (x Testinfo)Noofchar() int {
return x.noofchar
}

func main(){
var t Info
fmt.Println(x.Testinfo)
fmt.Println("No of char ",t.Noofchar())
x.noofchar++
fmt.Println("No of char ",t.Noofchar())
}

Am I referring to the method correctly by t.Noofchar() ? or there is something else that I am missing

  • 写回答

2条回答 默认 最新

  • douye5949 2013-01-23 21:35
    关注

    x is a variable to which you can assign anything that implements the Info interface. You've assigned nothing to that variable.

    Once you assign something, x.noofchar++ will not work because again x can hold anything that implements the Info interface, which means you can only access the methods defined by that interface. Interfaces do not allow direct access to fields.

    The only method defined in the Info interface is the Noofchar() int method, so that is the only way to interact with the value stored in x.

    The x defined by the method receiver (x Testinfo) isn't at all related to the var x Info variable. That x does have direct access to the struct fields.

    The t.Noofchar() calls are correct and will work.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度