英文:
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)}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论