从 GoLang 中的嵌套结构定义创建对象?
Create an object from nested struct definition in GoLang?
有没有办法从嵌套结构类型创建对象
func main() {
car := Car{}
var wheel Car.Wheel
}
type Car struct {
Wheel struct {
name string
}
}
我有一个很深的嵌套json。我有兴趣分别对这些嵌套结构中的许多进行操作。
我想通过“根”定义访问结构定义。 Car.Wheel
之类的东西,而不是为 json
中的许多嵌套对象显式定义 type Wheel struct
您是否正在寻找这样的东西:
package main
import "fmt"
type Car struct {
model string
wheel Wheel
}
type Wheel struct {
name string
}
func main() {
car := Car{model: "Toyota"}
car.wheel.name = "my wheel"
fmt.Println("car model: ", car.model)
fmt.Println("car wheel name:", car.wheel.name)
}
Is there a way to create an object from a nested struct type
不,因为没有“嵌套结构类型”这样的东西。你没有类型Car.Wheel
,你有类型Car
,有字段Wheel
;该字段的类型是未命名类型 struct { name string }
。您不能引用未命名的类型;它是未命名的。要引用一个类型,你必须给它命名。你可以这样做:
var wheel struct { name string }
并且您可以在 wheel
和 Car.Wheel
之间进行分配,因为它们是同一类型;然而,这不是特别方便(你必须在你使用它的任何地方写出完整的类型定义),这意味着你不能在类型上定义任何方法,这可能是也可能不是你关心的限制.
一般来说,在 Go 中,您只想为要使用的每种类型定义一个命名类型,并且这些定义都位于顶层:
type Car struct {
Wheel Wheel
}
type Wheel struct {
name string
}
有没有办法从嵌套结构类型创建对象
func main() {
car := Car{}
var wheel Car.Wheel
}
type Car struct {
Wheel struct {
name string
}
}
我有一个很深的嵌套json。我有兴趣分别对这些嵌套结构中的许多进行操作。
我想通过“根”定义访问结构定义。 Car.Wheel
之类的东西,而不是为 json
type Wheel struct
您是否正在寻找这样的东西:
package main
import "fmt"
type Car struct {
model string
wheel Wheel
}
type Wheel struct {
name string
}
func main() {
car := Car{model: "Toyota"}
car.wheel.name = "my wheel"
fmt.Println("car model: ", car.model)
fmt.Println("car wheel name:", car.wheel.name)
}
Is there a way to create an object from a nested struct type
不,因为没有“嵌套结构类型”这样的东西。你没有类型Car.Wheel
,你有类型Car
,有字段Wheel
;该字段的类型是未命名类型 struct { name string }
。您不能引用未命名的类型;它是未命名的。要引用一个类型,你必须给它命名。你可以这样做:
var wheel struct { name string }
并且您可以在 wheel
和 Car.Wheel
之间进行分配,因为它们是同一类型;然而,这不是特别方便(你必须在你使用它的任何地方写出完整的类型定义),这意味着你不能在类型上定义任何方法,这可能是也可能不是你关心的限制.
一般来说,在 Go 中,您只想为要使用的每种类型定义一个命名类型,并且这些定义都位于顶层:
type Car struct {
Wheel Wheel
}
type Wheel struct {
name string
}