将参数传递给函数参数不起作用
Passing parameter to a function parameter is not working
我写了下面的代码
package main
import (
"fmt"
"strings"
)
type student struct {
Name string
Age int
City string
}
func takeFuncAsParam(a func(st student, c string) bool, s []student) []student {
var result []student
for _, e := range s {
if a(e,c) {
result = append(result, e)
}
}
return result
}
func main() {
s1 := student{"Subir", 30, "Bolpur"}
s2 := student{"Mainak", 29, "Bolpur"}
s := []student{s1, s2}
filterByName := func(s student, c string) bool {
return strings.Contains(s.Name, c)
}
result := takeFuncAsParam(filterByName, s)
fmt.Println(result)
}
我在第 17 行遇到编译错误。
undefined: c
那么在这种情况下(c 字符串)如何将参数传递给 filterByName 函数?
将 takeFuncAsParam
的参数类型更改为 func(student) bool
,即删除 c string
参数,如下所示:
func takeFuncAsParam(fn func(student) bool, s []student) []student {
var result []student
for _, e := range s {
if fn(e) {
result = append(result, e)
}
}
return result
}
将 filterByName
更改为一个函数,该函数采用 name
参数进行过滤,returns 一个 takeFuncAsParam
所需类型的新函数,即func(student) bool
,像这样:
filterByName := func(name string) func(student) bool {
return func(s student) bool {
return strings.Contains(s.Name, name)
}
}
要使用新的过滤器函数,您需要使用 name
参数调用它以进行过滤,然后将返回的函数传递给 takeFuncAsParam
,如下所示:
fn := filterByName("Subir")
result := takeFuncAsParam(fn, s)
// or
result := takeFuncAsParam(filterByName("Subir"), s)
我写了下面的代码
package main
import (
"fmt"
"strings"
)
type student struct {
Name string
Age int
City string
}
func takeFuncAsParam(a func(st student, c string) bool, s []student) []student {
var result []student
for _, e := range s {
if a(e,c) {
result = append(result, e)
}
}
return result
}
func main() {
s1 := student{"Subir", 30, "Bolpur"}
s2 := student{"Mainak", 29, "Bolpur"}
s := []student{s1, s2}
filterByName := func(s student, c string) bool {
return strings.Contains(s.Name, c)
}
result := takeFuncAsParam(filterByName, s)
fmt.Println(result)
}
我在第 17 行遇到编译错误。
undefined: c
那么在这种情况下(c 字符串)如何将参数传递给 filterByName 函数?
将 takeFuncAsParam
的参数类型更改为 func(student) bool
,即删除 c string
参数,如下所示:
func takeFuncAsParam(fn func(student) bool, s []student) []student {
var result []student
for _, e := range s {
if fn(e) {
result = append(result, e)
}
}
return result
}
将 filterByName
更改为一个函数,该函数采用 name
参数进行过滤,returns 一个 takeFuncAsParam
所需类型的新函数,即func(student) bool
,像这样:
filterByName := func(name string) func(student) bool {
return func(s student) bool {
return strings.Contains(s.Name, name)
}
}
要使用新的过滤器函数,您需要使用 name
参数调用它以进行过滤,然后将返回的函数传递给 takeFuncAsParam
,如下所示:
fn := filterByName("Subir")
result := takeFuncAsParam(fn, s)
// or
result := takeFuncAsParam(filterByName("Subir"), s)