将命名类型转换为无名类型

huangapple go评论77阅读模式
英文:

Convert named types to unnamed types

问题

假设我有一个包含未命名类型的结构体 UnnamedTypes:

type UnnamedTypes struct {
    i []int
    f []float64
}

还有一些在结构体中命名的类型:

type I []int
type F []float64

type NamedTypes struct {
    i I
    f F
}

如何将 NamedTypes 结构体赋值给 UnnamedTypes 结构体最简单?

func main() {
    var u UnnamedTypes
    var n NamedTypes
    
    u.i = []int{1,2}
    u.f = []float64{2,3}
    
    n.i = []int{2,3}
    n.f = []float64{4,5}
    
    // 下面的赋值会失败,报错为 `cannot convert n (type NamedTypes) to type UnnamedTypes`
    u = UnnamedTypes(n)
}

以上代码中的赋值操作会失败,报错为 cannot convert n (type NamedTypes) to type UnnamedTypes

英文:

Say I have a struct of UnnamedTypes:

type UnnamedTypes struct {
	i []int
	f []float64
}

And some named types in a struct:

type I []int
type F []float64

type NamedTypes struct {
	i I
	f F
}

What's the easiest way to assign NamedTypes struct to an UnnamedTypes struct?

func main() {
	var u UnnamedTypes
	var n NamedTypes
	
	u.i = []int{1,2}
	u.f = []float64{2,3}
	
	n.i = []int{2,3}
	n.f = []float64{4,5}
	
	u = UnnamedTypes(n)
}

fails with cannot convert n (type NamedTypes) to type UnnamedTypes

答案1

得分: 3

使用旧的结构体值创建一个新的结构体值。

u := UnnamedTypes{
    i: n.i,
    f: n.f,
}

需要注意的是,因为这些特定的值是切片,两个不同结构体中的切片是完全相同的。修改一个切片将会修改另一个切片。对于指针(包括映射和接口)也是如此。如果你希望它们有自己的副本,你必须分配一个副本。

英文:

Create a new struct value using the old ones.

u = UnnamedTypes{
	i: n.i,
	f: n.f,
}

A warning though, because these specific values are slices, the slices in the two different structs are the exact same slices. Modifying one will modify the other. The same will apply to any pointers as well (including maps and interfaces). If you want them to have their own copy, you must allocate a copy.

huangapple
  • 本文由 发表于 2017年8月8日 03:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/45554548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定