-1

I need to do something like this:

// I have an interface with these two methods defined
type mapper interface {
    ReadMapper(interface{}) interface{}
    WriteMapper(interface{}) interface{}
}

then I need to assign ReadMapper and WriteMapper some functions which are defined somewhere else in the project. Is there is a way to do something like this in Go? Assigning functions to them?

   V1Mapper mapper
   V1Mapper.ReadMapper = functions()....
   V1Mapper.WriteMapper = functions()....

Then, I need another map and want the mapper as the value type and want to do something like below.

mappingFunctions := map[string]mapper

mappingFunctions ["some_string"] = V1Mapper 

and then from another file, I want to do this:

mappingFunctions["some_string"].ReadMapper(Data)

EDIT: I never asked for syntax in the question. I just wanted to know if there was a better way to do this because I was new to Go. I do agree I am not very much familiar with the syntax of the Go and I will have to go through the documentation (not once but many times).

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ray an
  • 1,132
  • 3
  • 17
  • 42
  • How about using a struct with functions instead of interface? – bereal Jun 02 '20 at 10:07
  • I just looked on the internet what u suggested (about using struct). Do u mean something like this??? `type mapper struct { ReadMapper func(interface{}) interface{} WriteMapper func(interface{}) interface{} }` – ray an Jun 02 '20 at 10:41
  • will this allow me to use dot notation to assign functions as values? – ray an Jun 02 '20 at 10:42
  • 1
    Please read through [A Tour of Go](https://tour.golang.org/welcome/1). It will take about 15 minutes, and should any basic syntax question like this. If you still have specific questions after that, let us know. – Jonathan Hall Jun 02 '20 at 10:43
  • @rayan yes, something like that. That struct would not implement any interface, but you can still can call the function and assign them. – bereal Jun 02 '20 at 10:43
  • 1
    People, this question is not about syntax. It's about design. – bereal Jun 02 '20 at 10:45

1 Answers1

2

If you want to compose mappers from the existing functions, you can use structures instead of interfaces:

type Mapper struct {
    ReadMapper  func(interface{}) interface{}
    WriteMapper func(interface{}) interface{}
}

mappers := map[string]*Mapper{}
mappers["some_name"] = &Mapper{
    ReadMapper: someFunc1,
    WriteMapper: someFunc2,
}

or

m := new(Mapper)
m.ReadMapper = someFunc1
m.WriteMapper = someFunc2
mappers["some_name"] = m
bereal
  • 32,519
  • 6
  • 58
  • 104