英文:
passing a method on an instance of a struct as a parameter
问题
我有一个接受函数作为参数的函数:
func send(n int, c func(x int) int) int {
return c(n)
}
我有一个定义在结构体上的方法:
type data struct {
value int
}
func (t *data) set(x int) {
t.value = x
}
我想创建一个结构体实例,并将方法set
绑定到该实例,然后将该实例作为第二个参数传递给send
函数,以便从send
函数中设置value
字段。
这种做法可行吗?
链接:https://play.golang.org/p/bv1JevQBcq
英文:
I have a function that accepts a function as a parameter:
func send(n int, c func(x int) int) int {
return c(n)
}
and I have a structure with a method defined on it
type data struct {
value int
}
func (t *data) set(x int) {
t.value = x
}
I would like to create an instance of the structure and pass method set
bound to this instance to the send
function as the second parameter, to set the value
field from send
.
Is this possible?
答案1
得分: 3
你可以使用方法值。这是类似于你的示例的代码:
package main
import "fmt"
func send(n int, c func(x int)) {
c(n)
}
type data struct {
value int
}
func (t *data) set(x int) {
t.value = x
}
func main() {
d := data{1}
fmt.Println(d)
send(2, d.set)
fmt.Println(d)
}
我无法使用问题中的类型,因为send函数的参数返回一个值,而方法没有返回值。如果你确实需要使用问题中的类型,那么可以使用匿名函数将方法适配为函数参数类型:
send(2, func(v int) int { d.set(v); return 0 })
英文:
You can use a method value. Here's something similar to your example:
package main
import "fmt"
func send(n int, c func(x int)) {
c(n)
}
type data struct {
value int
}
func (t *data) set(x int) {
t.value = x
}
func main() {
d := data{1}
fmt.Println(d)
send(2, d.set)
fmt.Println(d)
}
I could not use the types in the question because the function argument to send returns a value and the method does not. If you do need to use the types in the question, then use an anonymous function to adapt the method to the function argument type:
send(2, func(v int) int { d.set(v); return 0 })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论