dongwh1992 2018-12-10 15:09
浏览 48
已采纳

在编写可能最终被传递给任何类型的结构的函数时,可以将接口用作参数吗?

I am trying to write a function which could end up taking any kind of struct... let's say it is like this :

func setDate(s timestamp, data interface{}){
    data.Date = timestamp
}

I realize that I wouldn't need a function to set this value in real life, I am trying to learn more about how interfaces work, etc.

  • 写回答

1条回答 默认 最新

  • doujiang1939 2018-12-10 15:13
    关注

    You could approach it that way, but then inside setDate() you would need to use reflection to set the Date field. Go is a statically typed language, so if the (static) type of data is interface{} (which says nothing about it), you can't really do anything useful with it (you can't refer to its Date field, because there is no guarantee that its value has a Date field).

    Instead you should define a HasDate interface which contains a single method:

    type HasDate interface {
        SetDate(s time.Time)
    }
    

    The ability to set the date. And your function should expect a value of this interface type:

    func setDate(s time.Time, data HasDate) {
        data.SetDate(s)
    }
    

    Anyone who implements this HasDate interface can be passed to your setDate() function. Note that in Go implementing interfaces is implicit: there is no declaration of intent. This means any type that has a SetDate(time.Time) method implements this HasDate interface without even knowing this interface exists.

    This is an example type that implements it (more precisely its pointer *MyType):

    type MyType struct {
        date time.Time
    }
    
    func (mt *MyType) SetDate(s time.Time) {
        mt.date = s
    }
    

    Example testing it (try it on the Go Playground):

    mt := &MyType{}
    
    setDate(time.Now(), mt)
    
    fmt.Println(mt.date)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换