doushan5245 2017-11-18 08:29
浏览 17
已采纳

无法理解一些Go代码

While I was reading the code of package "net", I found some code like this:

// first returns the first address which satisfies strategy, or if
// none do, then the first address of any kind.
func (addrs addrList) first(strategy func(Addr) bool) Addr {
    for _, addr := range addrs {
        if strategy(addr) {
            return addr
        }
    }
    return addrs[0]
}

I am really confused about why the func first includes another func named func(Addr), and how does this code implement the behaviour which the comments say?

  • 写回答

3条回答 默认 最新

  • dshw124502 2017-11-18 09:38
    关注
    1 func (addrs addrList) first(strategy func(Addr) bool) Addr {
    2    for _, addr := range addrs {
    3        if strategy(addr) {
    4            return addr
             }
         }
    5    return addrs[0]
      }
    

    In words:

    1. function on addrs named first returns Addr takes strategy argument which must be a function that takes Addr and return bool.
    2. for each addr in range of addrs apply function strategy on addr
    3. if it (the strategy func) returns true
    4. then whole function first returns that addr
    5. whole function first return the very first [0] Addr from addrs, implied: which only happens if none of strategy calls on addr in range of addrs returned true.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序