duanhe1903
duanhe1903
2019-08-01 15:57
浏览 109
已采纳

接口[golang]中的字段?

is there any solution to force struct have specific property(defined in interface)?
or define a property(attribute,field) in interface?.
as i see interface is always accept method not property?. (https://gobyexample.com/interfaces)

type geo interface {
    PrintType()
    typ string//not function , but field
}
type circle struct {
    typ string
}

func (c circle) PrintType() {
    fmt.Println(c.typ)
}

thanks

图片转代码服务由CSDN问答提供 功能建议

是否有任何解决方案来强制 struct 具有特定的属性 (在 interface 中定义)?
\也没有在interface中定义属性(属性,字段)。
as我看到interface始终接受方法而不是property ?。 ( https://gobyexample.com/interfaces

  type geo interface {
 PrintType(  )
输入字符串//不起作用,但字段
} 
type圆结构{
输入字符串
} 
 
func(c圆)PrintType(){
 fmt.Println(c.typ)\  n} 
   
 
 

谢谢

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsf22567
    dsf22567 2019-08-01 16:03
    已采纳

    Interfaces are about methods only, not properties, because interfaces are about behavior. So there is no way to force a struct to have something. Rather the preferred method is to have an accessor to that member.

    点赞 评论

相关推荐