I want to be able to dynamically generate a method ApiName
for the following struct:
type SomeCustomSObject struct {
sobjects.BaseSObject
}
The interface I want to implement the method for is as follows:
type SObject interface {
ApiName() string
ExternalIdApiName() string
}
I would like to dynamically create the method as follows:
func createApiNameMethod(name, string) <return type> {
return func (t *SomeCustomSObject) ApiName() string {
return name
}
}
I know the code above does not work, but is there anyway to acheive this in Go?
You can't define methods inside a function, for details see Golang nested class inside function.
What you may do is create an implementation of
SObject
which is capable of dispatching to custom functions in its own implementation. An easy way to create such "proxy" implementation is to use a struct with fields of function types matching the types of the methods (without a receiver), and implement methods on this struct. The method implementations may simply forward the calls to the function values stored in the struct fields, and may have a default behavior if the appropriate field is not set. And you may change the values of the function fields, the behavior of the methods will be dynamic.Here's an example of it:
Testing it:
Output is as expected (try it on the Go Playground):
Of course in this simple example the
sobjimpl.apiName
function field could be left out entirely, it could have been enough to just store thename
and return that fromsobjimpl.ApiName()
. But the example shows how you may choose functions at runtime that will be called as the methods of an implementation.