go结构体嵌套的切片数组

package main

import (
	"fmt"
)

type XCDataStu struct {
	Id   int    `json:"id" 		xorm:"id"`
	Name string `json:"name" 	xorm:"name"`
}
type XCDataStu1 struct {
	Id             int    `json:"id" xorm:"id"`
	Str1           string `json:"str1" xorm:"str1"`
	Db1            string `json:"db1" xorm:"db1"`
	Device_type    string `json:"Device_type" xorm:"Device_type"`
	DeviceTypeName string `json:"DeviceTypeName"`
}
type XCDataStuAll struct {//结构体嵌套
	XCDataStuinall  XCDataStu
	XCDataStu1inall XCDataStu1
}

func main() {
/*1*/
	xcData := []XCDataStu{
		XCDataStu{Id: 758, Name: "David758"},
		XCDataStu{Id: 759, Name: "David759"},
	}
/*2*/
	xcdataall := make([]XCDataStuAll, len(xcData))

	/*xcdataall[0]={	XCDataStu{Id: 758, Name: "David758"},
	XCDataStu1{Id: 0, Str1: "dsa", Db1: "dsa",
		Device_type: "fhls", DeviceTypeName: "dasf"}}*/
	fmt.Println(len(xcData))
	fmt.Println(xcData[0])
	fmt.Println(xcData[1])
	i := 0
	for ; i < 2; i++ {
		xcdataall[i].XCDataStuinall.Id = xcData[i].Id
		xcdataall[i].XCDataStuinall.Name = xcData[i].Name
	}
	fmt.Println(xcdataall)

}


结构体切片:

  • 可以直接声明时初始化,如程序中的1
  • 可以用make,但是必须给定长度,否则不能使用下标进行赋值。如程序中的2
	var xcdataall []XCDataStuAll
	for ; i < 2; i++ {
		xcdataall[i].XCDataStuinall.Id = xcData[i].Id
		xcdataall[i].XCDataStuinall.Name = xcData[i].Name
	}

程序编译没错,但是最后运行后会出现panic。。。

panic: runtime error: index out of range

你可能感兴趣的:(golan)