将一个结构体实例的方法作为参数传递

huangapple go评论75阅读模式
英文:

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?

https://play.golang.org/p/bv1JevQBcq

答案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)
}

playground示例

我无法使用问题中的类型,因为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)
}

playground example

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 })

huangapple
  • 本文由 发表于 2015年1月24日 08:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/28120871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定