dongtangze6393 2017-07-29 11:37
浏览 9

结构内的功能。 为什么?

What is the use case/advantage of defining a function within a structure in go?

type demo struct {
    F func()
}
  • 写回答

2条回答 默认 最新

  • doubi4491 2017-07-29 11:47
    关注

    I think that the best answer would be an example.

    Look at Client.CheckRedirect in the documentation.

    type Client struct {
        // (...)
        CheckRedirect func(req *Request, via []*Request) error
    }
    

    This is a function that is being invoked whenever a http.Client has a redirect response. By the fact, that this function is a public property, you can set this when creating the Client object or afterwards and thus you can define custom behaviour on such case.

    client := &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        }
    }
    

    Function properties are just a delegates of custom behaviour (and not only!).

    Another example would be creating an object which has an event.

    type Example struct {
        EventHandler func(params []interface{})
    }
    

    You can specify a behaviour on that event by setting the Example.EventHandler property.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向