douza1373 2017-12-25 00:11
浏览 110


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 {

I would expect that if I define a User:

a := User{
        Email:    "",
        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?

  • 写回答

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.

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

    package main
    import (
    type User struct {
        Email    string `json:"email"`
        Password string `json:"password"`
    type PublicUser User
    func main() {
        a := User{
            Email:    "",
            Password: "1234",
    ", a)
        // out: User{Email:"", Password:"1234"}
        b := PublicUser(a)
        fmt.Printf("%#v", b)
        // out PublicUser{Email:"", 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 (

    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.

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



  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on发生意外错误: 5无法连接到 MQTT 代理,如何解决?