在Go中扩展未命名类型
因此,以下工作:在Go中扩展未命名类型,go,Go,因此,以下工作: type Individual [][]int type Population []*Individual 我要做的是在人口中添加一个字段,所以我执行以下操作 var p Population p.Name = "human" 所以我试了一下: type Individual [][]int type Population struct { []*Individual Name string } 但这对我不起作用。如何执行此操作?您应该为结构的字段声明
type Individual [][]int
type Population []*Individual
我要做的是在人口中添加一个字段,所以我执行以下操作
var p Population
p.Name = "human"
所以我试了一下:
type Individual [][]int
type Population struct {
[]*Individual
Name string
}
但这对我不起作用。如何执行此操作?您应该为结构的字段声明一个名称:
package main
import (
"fmt"
)
type Individual [][]int
type Population struct {
Individual []*Individual // <- A name for field
Name string
}
func main() {
var p Population
p.Name = "human"
fmt.Printf("%+v", p)
}
但是我不能在p上迭代。我希望我能为{,I:=range p{…}而不是为{,I:=range p.{…}@qzvrwxce
range
只支持切片
,数组
,通道
和映射
,不能范围
覆盖结构字段,因此range p.Individual
是唯一的选择。
=> {Individual:[] Name:human}