Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Create method on defined struct using reflection #20189

Closed
apoloa opened this issue May 1, 2017 · 1 comment
Closed

Proposal: Create method on defined struct using reflection #20189

apoloa opened this issue May 1, 2017 · 1 comment

Comments

@apoloa
Copy link

apoloa commented May 1, 2017

It would be good create functions using reflection inside the struct already defined.

Like this:

package main

import (
	"fmt"
	"reflect"
)

type Manager struct{}

func main() {

	swap := func(in []reflect.Value) []reflect.Value {
		return []reflect.Value{in[1], in[0]}
	}

	makeSwap := func(fptr interface{}) {
		fn := reflect.ValueOf(fptr).Elem()
		v := reflect.MakeFunc(fn.Type(), swap)
		fn.Set(v)
	}

	var intSwap func(int, int) (int, int)
	makeSwap(&intSwap)

	var floatSwap func(float64, float64) (float64, float64)
	makeSwap(&floatSwap)

	manager := &Manager{}
	st := reflect.ValueOf(manager).Elem()
	st.MethodByName("IntSwap").Set(reflect.ValueOf(intSwap))
	st.MethodByName("FloatSwap").Set(reflect.ValueOf(floatSwap))
	fmt.Println(intSwap(0, 1)) // 1 0
	fmt.Println(manager.IntSwap(0,1)) // 1 0
	fmt.Println(floatSwap(2.72, 3.14)) // 3.14 2.72
	fmt.Println(manager.FloatSwap(2.72, 3.14)) // 3.14 2.72
}
@bradfitz bradfitz changed the title Proposal Create method on defined struct using reflection Proposal: Create method on defined struct using reflection May 1, 2017
@gopherbot gopherbot added this to the Proposal milestone May 1, 2017
@ianlancetaylor
Copy link
Contributor

As a general rule, the reflect package should provide exactly the capabilities of the language. In the language you can not define a method on an existing struct, so reflect shouldn't let you do it either.

Also, if you could define a struct in one package and add methods in another the general handling of interface conversion would be inconsistent, depending on whether the methods had been added or not.

I think that reduces this to a dup of #16522.

I'm going to close this, but please comment if you disagree.

@golang golang locked and limited conversation to collaborators May 1, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants