在Golang中转换组合类型

时间:2017-12-25 00:11:21

标签: go

我在Golang中使用reading about类型别名和组合结构。我希望能够有两个结构相同但可以很容易地相互转换的结构。

我的父结构定义为:

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

组合结构定义为:

type PublicUser struct {
    *User
}

如果我定义User

,我希望如此
a := User{
        Email:    "admin@example.net",
        Password: "1234",
    }

然后我可以执行以下类型转换:

b := (a).(PublicUser)

但它因类型断言无效而失败:

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

如何在Go中转换结构相似的类型?

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

1 个答案:

答案 0 :(得分:1)

在Go中键入断言让您点击界面的具体类型,而不是结构:

  

类型断言提供对接口值的基本具体值的访问   https://tour.golang.org/methods/15

但是,稍作修改,此代码可以正常工作,并且可能正如您所期望的那样:

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\n", a)
    // out: User{Email:"admin@example.net", Password:"1234"}

    b := PublicUser(a)
    fmt.Printf("%#v", b)
    // out PublicUser{Email:"admin@example.net", Password:"1234"}
}

此处,PublicUserUser类型的重新定义;最重要的是,它是独立类型,共享字段,但不共享用户(https://golang.org/ref/spec#Type_definitions)的方法集。

然后,您可以简单地使用PublicUser类型构造函数,因为您可能使用string / []byte次转换执行类似操作:foo := []byte("foobar")

另一方面,如果您要使用实际的type aliastype PublicUser = User),则输出会将User列为两个实例的类型:PublicUser只是一个新名称旧事物,不是新类型。