gpt4 book ai didi

go - 在 Golang 中转换组合类型

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:03 34 4
gpt4 key购买 nike

我去过 reading about Golang 中的类型别名和组合结构。我希望能够拥有两个结构相同但可以在彼此之间轻松转换的结构。

我有一个父结构定义为:

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

最佳答案

Go 中的类型断言让您可以使用接口(interface)的具体类型,而不是结构:

A type assertion provides access to an interface value's underlying concrete value.
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"}
}

这里,PublicUser是对User类型的重新定义;最重要的是,它是一个独立的类型,共享字段,但不共享 User 的方法集(https://golang.org/ref/spec#Type_definitions)。

然后,您可以简单地使用 PublicUser 类型构造函数,就像您可能对 string/[]byte 转换所做的类似:foo := [ ]byte("foobar").

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

关于go - 在 Golang 中转换组合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964820/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com