douza1373 2017-12-25 00:11
浏览 110
已采纳

在Golang中转换组合类型

I've been reading about type alias and composed structs in Golang. I want to be able to have two structs which are structurally identical but can be easily converted between each other.

I have a parent structure defined as:

type User struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

And a composed struct defined as:

type PublicUser struct {
    *User
}

I would expect that if I define a User:

a := User{
        Email:    "admin@example.net",
        Password: "1234",
    }

I could then perform the following type conversion:

b := (a).(PublicUser)

But it fails with an invalid type assertion:

invalid type assertion: a.(PublicUser) (non-interface type User on left)

How can I convert between structurally similar types in Go?

https://play.golang.org/p/I0VqrflOfXU

  • 写回答

1条回答 默认 最新

  • dongtu0363 2017-12-25 00:47
    关注

    Type assertions in Go let you tap into an interface's concrete type, not into structs:

    A type assertion provides access to an interface value's underlying concrete value.
    https://tour.golang.org/methods/15

    However, with slight modifications, this code works and probably behaves as you would expect:

    package main
    
    import (
        "fmt"
    )
    
    type User struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    }
    
    type PublicUser User
    
    func main() {
        a := User{
            Email:    "admin@example.net",
            Password: "1234",
        }
        fmt.Printf("%#v
    ", a)
        // out: User{Email:"admin@example.net", Password:"1234"}
    
        b := PublicUser(a)
        fmt.Printf("%#v", b)
        // out PublicUser{Email:"admin@example.net", Password:"1234"}
    }
    

    Here, PublicUser is a redefinition of the User type; most importantly, it is a standalone type, shares the fields, but not the method set of User (https://golang.org/ref/spec#Type_definitions).

    Then, you can simply use the PublicUser type constructor, as you might have been doing similarly with string/[]byte conversions: foo := []byte("foobar").

    If, on the other hand, you were to use an actual type alias (type PublicUser = User) your output will list User as type for both instances: PublicUser is only a new name for the old thing, not a new type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法