在Go中扩展未命名的类型

问题描述 投票:0回答:1

以下是有效的:

type Individual [][]int
type Population []*Individual

我要做的是为人口添加一个字段,所以我做了以下几点

var p Population
p.Name = "human"

所以我尝试了这个:

type Individual [][]int
type Population struct {
     []*Individual
     Name string
}

但它对我不起作用。我该怎么做呢?

go
1个回答
1
投票

您应该声明结构字段的名称:

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)
}

playground

=> {Individual:[] Name:human}
© www.soinside.com 2019 - 2024. All rights reserved.