-3

I want to merge some similar func code to one func, but every old func is use different type of struct, so i intend to create the model by different string of type. SO i do something like this:

type A struct {
   filed string
}
type B struct {
   filed string
}
and still C, D, E, F here...(every struct has its own method different with others)

and i want create those type in one place:

create(typeName string) interface {
   switch typeName {
   case A:
       return &A{}
   case B:
       return &B{}
   ....(more case than 10 times)
   }
}

Then i use the create() here:

model := create("A")

now, model is type of interface, and no A`s fileds, how would simply to recover the type of model to A

Otis
  • 5
  • 1
  • 1
    Does this answer your question? [How to cast interface {} to struct](https://stackoverflow.com/questions/50852393/how-to-cast-interface-to-struct) – Blokje5 Jun 11 '20 at 10:21

1 Answers1

0

Here is a sample of how you can use type assertion to convert interfaces to underlying structs

Here e is of the struct type and hence you can access any of its fields or struct methods.

package main

import (
    "fmt"
)

type A struct {
    AF int
}

type B struct {
    BF string
}

func main() {
    ds := []interface{}{
        A{1},
        B{"foo"},
    }

    for _, d := range ds {
        switch e := d.(type) {
        case A:
            fmt.Println(e.AF)
        case B:
            fmt.Println(e.BF)
        }
    }
}
poWar
  • 745
  • 6
  • 15
  • thanks for help. Would there is a way to avoid using `type assertion`, there are too much switch/case and broken the original logic. I hope i can use the `Model` just like original type – Otis Jun 11 '20 at 10:57
  • Unfortunately, there is no other way. You pay for abstraction as much as it really costs. – user3524337 Jun 11 '20 at 17:55