Home > Back-end >  Converting enum type to *enum type in go
Converting enum type to *enum type in go

Time:10-16

go newbie here, I want to convert an enum from Day type to *Mappings type, since they are strings, I am unable to assign pointer values to the enum directly. I tried to assign the value to a temporary variable

var id = MON
*r = id

but that didn't work, I want it to be assigned to a pointer so that I can have nil values for the type. I can't change the Day struct or Mappings struct type. How can I assign the value to the receiver *r without running into the pointer issue? playground link: https://play.golang.org/p/5SNx0I-Prc2

package main

type Day string

const (
    SUNDAY  Day = ""
    MONDAY  Day = "MONDAY"
    TUESDAY Day = "TUESDAY"
)

type Mappings string

const (
    SUN Mappings = ""
    MON Mappings = "MON"
    TUE Mappings = "TUE"
)

func main() {

    type A struct {
        day Day
    }

    type B struct {
        day *Mappings
    }

    sourceObj := A{day: MONDAY}

    destObj := B{}

    destObj.day.To(sourceObj.day)

}

func (r *Mappings) To(m Day) {
    switch m {
    case MONDAY:
        *r = MON
    case TUESDAY:
        *r = TUE
    }
}

CodePudding user response:

destObj.day will be nil. Hence, *r and *destObj.day will be a run time exception. Allocate space for destObj.day by using the new keyword. Example:

destObj := B{new(Mappings)}
  • Related