Golang中如何给[]struct赋值

Golang中如何给[]struct赋值

type example struct {
Example          string  `json:"example"`
Persons               []struct {
	FirstName     string `json:"firstName"`
	LastName      string `json:"lastName"`
	MiddleName    string `json:"middleName"`
	PhoneNumber   []struct {
		Carrier string `json:"carrier"`
                   Number string `json:"number"`
	} `json:"phoneNumber"`
   } `json:"persons"`
}

我有这个示例结构体,想要创建该结构体的实例

var ex example
ex.Example = "example"
ex.Persons[0].FirstName = "JHON"
ex.Persons[0].LastName = "DOE"
ex.Persons[0].MiddleName = "TEST"
ex.Persons[0].PhoneNumber[0].Carrier = "AT&T"
    ex.Persons[0].PhoneNumber[0].Number= "123545568"

但是我遇到了索引越界错误,如何为 Person []Struct 赋值?


更多关于Golang中如何给[]struct赋值的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

或者你也可以使用字面量创建切片:

type A struct {
  Field string
}

a := []A{
  A{ Field: "first" },
  A{ Field: "second" },
}

更多关于Golang中如何给[]struct赋值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在你的示例中,需要为Person切片分配空间,因为切片不是数组。它们就像指针,但带有长度和容量参数 😊 你最好将Person定义为单独的类型,然后像这样将其添加到主结构中:

type PhoneNumber struct {
	Carrier string `json:"carrier"`
	Number  string `json:"number"`
}

type Person struct {
	FirstName    string        `json:"firstName"`
	LastName     string        `json:"lastName"`
	MiddleName   string        `json:"middleName"`
	PhoneNumbers []PhoneNumber `json:"phoneNumber"`
}

type example struct {
	Example string   `json:"example"`
	Persons []Person `json:"persons"`
}

func main() {
	ex := example{
		Example: "example",
		Persons: []Person{
			Person{
				FirstName:  "JHON",
				LastName:   "DOE",
				MiddleName: "TEST",
				PhoneNumbers: []PhoneNumber{
					PhoneNumber{
						Carrier: "AT&T",
						Number:  "123545568",
					},
				},
			},
		},
	}
	fmt.Println(ex)
}

请检查:

  1. acbScoring 不存在(可能您指的是 “ex”)
  2. 为 PhoneNumber 创建一个结构体,为 Person 创建另一个结构体

例如:

package main

type PhoneNumber struct {
	Carrier string `json:"carrier"`
	Number  string `json:"number"`
}

type Person struct {
	FirstName    string        `json:"firstName"`
	LastName     string        `json:"lastName"`
	MiddleName   string        `json:"middleName"`
	PhoneNumbers []PhoneNumber `json:"phoneNumber"`
}

type example struct {
	Example string   `json:"example"`
	Persons []Person `json:"persons"`
}

func main() {
	var ex example
	ex.Example = "example"

	ex.Persons = make([]Person, 10)
	ex.Persons[0].FirstName = "JHON"
	ex.Persons[0].LastName = "DOE"
	ex.Persons[0].MiddleName = "TEST"

	ex.Persons[0].PhoneNumbers = make([]PhoneNumber, 10)
	ex.Persons[0].PhoneNumbers[0].Carrier = "AT&T"
	ex.Persons[0].PhoneNumbers[0].Number = "123545568"
}

在Go语言中,当你声明一个切片但未初始化时,它的值为nil,长度为0。直接通过索引访问会导致panic。你需要先初始化切片和嵌套的结构体。

以下是正确的赋值方法:

package main

import "fmt"

type example struct {
    Example string `json:"example"`
    Persons []struct {
        FirstName   string `json:"firstName"`
        LastName    string `json:"lastName"`
        MiddleName  string `json:"middleName"`
        PhoneNumber []struct {
            Carrier string `json:"carrier"`
            Number  string `json:"number"`
        } `json:"phoneNumber"`
    } `json:"persons"`
}

func main() {
    var ex example
    ex.Example = "example"
    
    // 初始化Persons切片并添加第一个元素
    ex.Persons = make([]struct {
        FirstName   string `json:"firstName"`
        LastName    string `json:"lastName"`
        MiddleName  string `json:"middleName"`
        PhoneNumber []struct {
            Carrier string `json:"carrier"`
            Number  string `json:"number"`
        } `json:"phoneNumber"`
    }, 1)
    
    ex.Persons[0].FirstName = "JHON"
    ex.Persons[0].LastName = "DOE"
    ex.Persons[0].MiddleName = "TEST"
    
    // 初始化PhoneNumber切片并添加第一个元素
    ex.Persons[0].PhoneNumber = make([]struct {
        Carrier string `json:"carrier"`
        Number  string `json:"number"`
    }, 1)
    
    ex.Persons[0].PhoneNumber[0].Carrier = "AT&T"
    ex.Persons[0].PhoneNumber[0].Number = "123545568"
    
    fmt.Printf("%+v\n", ex)
}

更简洁的方法是使用字面量初始化:

package main

import "fmt"

type example struct {
    Example string `json:"example"`
    Persons []struct {
        FirstName   string `json:"firstName"`
        LastName    string `json:"lastName"`
        MiddleName  string `json:"middleName"`
        PhoneNumber []struct {
            Carrier string `json:"carrier"`
            Number  string `json:"number"`
        } `json:"phoneNumber"`
    } `json:"persons"`
}

func main() {
    ex := example{
        Example: "example",
        Persons: []struct {
            FirstName   string `json:"firstName"`
            LastName    string `json:"lastName"`
            MiddleName  string `json:"middleName"`
            PhoneNumber []struct {
                Carrier string `json:"carrier"`
                Number  string `json:"number"`
            } `json:"phoneNumber"`
        }{
            {
                FirstName:  "JHON",
                LastName:   "DOE",
                MiddleName: "TEST",
                PhoneNumber: []struct {
                    Carrier string `json:"carrier"`
                    Number  string `json:"number"`
                }{
                    {
                        Carrier: "AT&T",
                        Number:  "123545568",
                    },
                },
            },
        },
    }
    
    fmt.Printf("%+v\n", ex)
}

或者使用append方法动态添加元素:

package main

import "fmt"

type example struct {
    Example string `json:"example"`
    Persons []struct {
        FirstName   string `json:"firstName"`
        LastName    string `json:"lastName"`
        MiddleName  string `json:"middleName"`
        PhoneNumber []struct {
            Carrier string `json:"carrier"`
            Number  string `json:"number"`
        } `json:"phoneNumber"`
    } `json:"persons"`
}

func main() {
    var ex example
    ex.Example = "example"
    
    // 使用append添加Person
    ex.Persons = append(ex.Persons, struct {
        FirstName   string `json:"firstName"`
        LastName    string `json:"lastName"`
        MiddleName  string `json:"middleName"`
        PhoneNumber []struct {
            Carrier string `json:"carrier"`
            Number  string `json:"number"`
        } `json:"phoneNumber"`
    }{
        FirstName:  "JHON",
        LastName:   "DOE",
        MiddleName: "TEST",
    })
    
    // 使用append添加PhoneNumber
    ex.Persons[0].PhoneNumber = append(ex.Persons[0].PhoneNumber, struct {
        Carrier string `json:"carrier"`
        Number  string `json:"number"`
    }{
        Carrier: "AT&T",
        Number:  "123545568",
    })
    
    fmt.Printf("%+v\n", ex)
}

推荐使用字面量初始化的方式,代码更清晰易读。

回到顶部