Reputation: 97
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
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
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:
addrs
named first
returns Addr
takes strategy
argument which must be a function that takes Addr
and return bool
.for
each addr
in range
of addrs
apply function strategy
on addr
strategy
func) returns true
first
returns that addr
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
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