Language feature request: bind object+method as function pointer

2,137 views
Skip to first unread message

Erik Unger

unread,
Aug 29, 2012, 5:37:07 AM8/29/12
to golan...@googlegroups.com
I think it would be useful to extend the language to allow binding of object + method as a function value that can be called without having to pass the object as first argument.

Why? I have seen multiple instances of reflection being used to wrap method calls by using an object pointer and the method name as string. This dynamic behavior wouldn't be necessary, if bound methods and functions could be called with the same interface.

reflect.Value.Method() already does method binding, why not have it in the language?

Of course, a binary function pointer compatible implementation would be tricky, but not impossible.
The function code that prepends the address of the object to argument list could get generated on the fly when an object+method gets assigned to a function pointer.

-Erik

roger peppe

unread,
Aug 29, 2012, 5:45:50 AM8/29/12
to Erik Unger, golan...@googlegroups.com
On 29 August 2012 10:37, Erik Unger <ung...@gmail.com> wrote:
> I think it would be useful to extend the language to allow binding of object
> + method as a function value that can be called without having to pass the
> object as first argument.

This is issue 2280.

There's no need to use reflection to do this, BTW - you
can use a simple closure.

x := os.Stdout
writeString := func(s string) (int, error) {
return x.WriteString(s)
}
writeString("foo\n")

Miki Tebeka

unread,
Aug 31, 2012, 10:41:13 AM8/31/12
to golan...@googlegroups.com

Peter S

unread,
Aug 31, 2012, 6:03:55 PM8/31/12
to Miki Tebeka, golan...@googlegroups.com
The "Pointer to method" in the linked thread represents the method of the type as a function which can be called with any instance. That is, the receiver instance has to be passed as the first parameter when invoking the pointed function. Example code by Ian Lance Taylor from the linked thread (comment mine):

type Foo struct{}
func (f *Foo) Method() {
    fmt.Println("Method")
}

func main() {
    var foo Foo
    fn := (*Foo).Method
    fn(&foo) // receiver instance passed as parameter
}

The feature proposed in Issue 2280 and in this thread would represent the method of a specific instance as a function value. That is, the receiver instance is decided when the function value is obtained, and the caller of the function value only provides the method parameters. An example based on the previous one would be:

func main() {
    var foo Foo
    fn := foo.Method // not valid in Go1
    fn() // receiver is "foo", no parameters needed
}

In Go1, the equivalent can be achieved using a closure. It is short in this example, but it gets longer and more difficult to read when the method has more parameters:

func main() {
    var foo Foo
    fn := func() { foo.Method() }
    fn()
}

Peter
Reply all
Reply to author
Forward
0 new messages