将枚举类型转换为Go中的*枚举类型

huangapple go评论71阅读模式
英文:

Converting enum type to *enum type in go

问题

新手上路
我想将一个类型为`Day`的枚举转换为`*Mappings`类型因为它们都是字符串所以我无法直接将指针值赋给枚举
我尝试将值赋给一个临时变量

var id = MON
*r = id

但是这样不起作用,我希望它被赋给一个指针,这样我就可以为该类型设置nil值。我不能更改`Day`结构体或`Mappings`结构体类型。
如何在不遇到指针问题的情况下将值赋给接收器`*r`?
playground链接: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
        }
    }
英文:

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
	}
}

答案1

得分: 6

destObj.day将是nil。因此,*r*destObj.day将引发运行时异常。
通过使用new关键字为destObj.day分配空间。
示例:

destObj := B{new(Mappings)}
英文:

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)}

huangapple
  • 本文由 发表于 2021年10月14日 01:38:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69559963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定