I have a type implementation:

type A struct{ name string } func (a A) getName() string { return "My name is " + a.name } 

How to change the implementation of the getName method at runtime?

Update

Redefinition in such a way that before the redefinition of "a.getName ()" caused the described implementation, and after the redefinition of the new.

  • @DarkGenius, clarify your question. Do you mean overload, redefinition or something else? - Nicolas Chabanovsky
  • @Expert, updated the question. - DarkGenius

2 answers 2

Fukntia is the ultimate value in Go. You can make this name a field, and assign it a value:

 package main type Typ struct { foo func () } func main() { t := Typ{} t.foo = func () { println("first implementation") } t.foo() t.foo = func () { println("second implementation") } t.foo() } 

will issue:

 first implementation second implementation 

UPD : If you want exactly the method, then you can call a variable field in the method.

 package main type A struct { } var globalFoo = func () string { return "first" } func (a A) getName() string { return globalFoo() } func main() { a := A{} println(a.getName()) globalFoo = func () string { return "second" } println(a.getName()) } 

But the fact that you want this is already alarming.

  • @Vladimir Gordeev, thanks for the amendment. - Alex Krass
  • @Alex Krass, you need a solution for the case when foo is not defined in the type (see the example in question). - DarkGenius
  • @DarkGenius for example, store in a global variable, updated - Vladimir Gordeev
  • It is unlikely that this is exactly what the vehicle wanted (asked). It was not the implementation that changed, but the link. In addition, both implementations were present in the code initially. - avp
  • one
    all because of the fact that the vehicle requested, thank God, it cannot be done - Vladimir Gordeev

And why do you need to change the implementation itself?

 type A struct { name string } func (a A) returnString(n string, b bool) string { if n != "" { return "My name is " + n } else if b { return "My name is " + "Петя" } else { return "My name is " + a.name } } a := A{"Вася"} fmt.Println(a.returnString("", false)) fmt.Println(a.returnString("Дима", false)) fmt.Println(a.returnString("", true)) My name is Вася My name is Дима My name is Петя 

This is a simple example, you can do something more beautiful.

  • You proceed from the assumption that the original type of method can be arbitrary. However, according to the condition of the problem, it is fixed, it cannot be changed. - DarkGenius