Assigning a struct (Having one of its fields as a struct) to another struct using the feature introduced in Go 1.8

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

Assigning a struct (Having one of its fields as a struct) to another struct using the feature introduced in Go 1.8

问题

我知道自从Go 1.8版本以来,可以像这样将一个结构体赋值给另一个结构体类型:

func example() {
	type T1 struct {
		X int `json:"foo"`
	}
	type T2 struct {
		X int `json:"bar"`
	}
	var v1 T1
	var v2 T2
	v1 = T1(v2) // 现在是合法的
}

然而,如果结构体内部的一个字段是另一个结构体,这种方式就不起作用。

Playground: https://play.golang.org/p/tSHdjBhhAJ

在这种情况下,除了手动分配每个字段之外,有什么最好的方法来分配两个结构体呢?

这不是一个重复的问题https://stackoverflow.com/questions/31981592/assign-struct-with-another-struct,因为在这里,你是将一个结构体赋值给另一个相同类型的结构体。然而,我想要的是将两个具有相同字段名的不同结构体进行赋值。

英文:

I'm aware that since Go 1.8 it's possible to assign one struct to another struct type like this:

func example() {
type T1 struct {
X int
json:"foo"
}
type T2 struct {
X int
json:"bar"
}
var v1 T1
var v2 T2
v1 = T1(v2) // now legal
}

However, if the struct internally has one of its fields as another struct, it doesn't work.

Playground: https://play.golang.org/p/tSHdjBhhAJ

What is the best way to assign 2 structs in this case apart from manually assigning each field?

This is not a duplicate of https://stackoverflow.com/questions/31981592/assign-struct-with-another-struct since here, you're assigning a struct to another struct of the same type. However what I want is assigning two different structs having the same field names.

答案1

得分: 3

新的Go 1.8功能只有在结构体具有相同的字段名和类型时才起作用。尽管Test2和Test4结构体在字段上是相同的,但它们是两种不同的类型,因此编译器不允许它们之间的赋值。有人可能会认为应该进行深度比较而不是简单的类型比较,但目前并不是这样实现的。你有三个选择:在每个结构体字段中使用相同的结构体类型,使用每个结构体中的匿名结构体(https://play.golang.org/p/Hw7HANwqbZ),或者编写一个辅助函数手动转换这两个结构体。

目前有一个提案,允许在没有逐个字段辅助方法的情况下转换具有深度等效的结构体,但目前计划在Go 2.x中实现:https://github.com/golang/go/issues/20621

英文:

The new Go 1.8 feature only works if the structures have the same field names and types. Despite the fact that your Test2 and Test4 structures are identical by fields, they are two separate types, and thus the compiler disallows their assignment. One might argue that structures should be deep-compared instead of a simple type comparison, but that's not how it's implemented currently. You have three options: use the same struct type for the struct field in each, use an anonymous struct in each (https://play.golang.org/p/Hw7HANwqbZ), or make a helper function to convert the two manually.

There's currently a proposal out to allow deeply-equivalent structures to be converted without a field-by-field helper method, but it is currently slated for Go 2.x: https://github.com/golang/go/issues/20621

huangapple
  • 本文由 发表于 2017年6月20日 17:12:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/44648735.html
匿名

发表评论

匿名网友

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

确定