0

I would like read, extract and save data from different sources with Read and Write methods implemented in Process interface The code works rigth in the first example:

type Process interface {
    Read()
    write() string
}

type Nc struct {
    data string
}

type Ctd Nc
type Btl Nc

func (nc *Ctd) Read() {
    nc.data = "CTD"
}
func (nc *Ctd) Write() string {
    return nc.data
}
func (nc *Btl) Read() {
    nc.data = "BTL"
}
func (nc *Btl) Write() string {
    return nc.data
}

func main() {
    var ctd = new(Ctd)
    var btl= new(Btl)
    ctd.Read()
    btl.Read()
    fmt.Println(ctd.Write())
    fmt.Println(btl.Write())
}

Now, I would like dynamically read data from files, methods get_config should return a constant type that I would like process in switch block as :

func main() {
    // bitMask = get_config()
    bitMask := 1
    // or bitmask := 2
    var nc = new(Nc)
    switch bitMask {
    case 1:
        nc = Ctd(nc)
    case 2:
        nc = Btl(nc)
    }
    nc.Read()
    fmt.Println(nc.Write())
}

I don't know how to declare nc with rigth type outside switch block

Thanks,

1 Answers1

0

In the interface the method write is lowercase so it is private. And the structs Ctd and Btl do not implement this interface as they have Write method uppercased.

So:

type Process interface {
    Read()
    Write() string
}

....

func main() {
  bitMask := 2
  // or bitMask := 2
  var nc Process
  switch bitMask {
  case 1:
    nc = &Ctd{}
  case 2:
    nc = &Btl{}
  }
  nc.Read()
  fmt.Println(nc.Write())
}

http://play.golang.org/p/IORCIY4z6B

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85