0

The title basically says it all..

Can I create a Go method that returns another Go method, at runtime? A simple example:

type Person struct {
    name string
    age uint
}

func (p Person) createGetNameMethod() /*return signature is a method for Person*/ {
    return /*return a new anonymous method here for Person*/
}
blackgreen
  • 34,072
  • 23
  • 111
  • 129
G4143
  • 2,624
  • 4
  • 18
  • 26

1 Answers1

6

Are Go methods first class functions?

Yes, they are.

Can I create a Golang method that returns another Golang method [...]?

Yes, of course.

[Can I] return a new anonymous method [?]

No, of course not.

The set of methods is determined at compile time. Methods are normal, first class functions, but they cannot be changed or created during runtime:

  • You can return a method that exists in the method set, but you cannot add one to the method set.

  • Reflection allows something like that but not in your case.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Volker
  • 40,468
  • 7
  • 81
  • 87
  • 2
    @g4143, note that what you _can_ do is to return an anonymous function which closes over the `name` field of the method's receiver, `p`, it is created in. Note a few caveats though: 1) in your particular case the contents of `p` is a copy of the value stored in a variable of type `Person` on which you call your method; hence if you were to return a closure from that method, I'd close over the field of the variable `p` not the original variable; 2) the resulting code would be quite convoluted; during a review, I'd ask what it was meant to actually achieve ;-) – kostix Jan 13 '22 at 08:00
  • @kostix, yes that is a possibility if the signature doesn't matter. – G4143 Jan 13 '22 at 11:27