user8645601
user8645601

Reputation: 97

can't understand some Go code

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?

Upvotes: 2

Views: 126

Answers (3)

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12835

Func first accepts as an argument strategy another function with type func(Addr) bool. So second function should take an Addr as input and return bool whether adder is ok.

As first such Addr found first function exits and returns it.

Logins is similar to filters - iterate a list until first matching value is found.

And as a last resort if for no one Addr value was got positive reply first function returns a first value in slice.

Upvotes: 1

k1m190r
k1m190r

Reputation: 1313

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.

Upvotes: 2

CallMeLoki
CallMeLoki

Reputation: 1361

consider strategy as a filter function, it just checks if addr in the range loop can pass the filter or not another and completely equal way to do this is like

func strategy(addr Addr) bool {
    if addr == ... {
        return true
    }

    return false
}

func main(){
    addr := first(strategy)
}

Upvotes: 1

Related Questions