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

補充:go遍歷結構體(struct)字段對應的值,切片(slice),字典(map)

一、遍歷結構體字段:

eg1:

package main
import (
    "fmt"
    "reflect"
)
type person struct {
    name string
    age  int
}
func main() {
    v := reflect.ValueOf(person{"steve", 30})
    count := v.NumField()
    for i := 0; i < count; i++ {
        f := v.Field(i)
        switch f.Kind() {
        case reflect.String:
            fmt.Println(f.String())
        case reflect.Int:
            fmt.Println(f.Int())
        }
    }
}

輸出結果:

steve

30

eg2:

package main
import (
    "fmt"
    "reflect"
)
type NotknownType struct {
    s1, s2, s3 string
}
var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
func main() {
    value := reflect.ValueOf(secret)
    for i := 0; i < value.NumField(); i++ {
        fmt.Printf("Field %d: %v\n", i, value.Field(i))
    }
}

輸出結果:

Field 0: Ada

Field 1: Go

Field 2: Oberon

二、遍歷切片:

for range 結構

package main
import (
    "fmt"
)
func main(){
    slice := []string{"hello","world","hello","everyone!"}
    for k,val:=range slice{
        fmt.Printf("slice %d is :%s\n",k,val )
    }
}

輸出結果:

slice 0 is :hello

slice 1 is :world

slice 2 is :hello

slice 3 is :everyone!

三、遍歷map:

package main
import (
    "fmt"
)
func main() {
    m := make(map[string]string)
    m["1"] = "hello"
    m["2"] = "world"
    m["3"] = "go"
    m["4"] = "is"
    m["5"] = "cool"
    fmt.Printf("The corresponding relationship between key and value is:\n")
    for key, val := range m {
        fmt.Printf("%v===>%v\n", key, val)
    }
}

輸出結果:

The corresponding relationship between key and value is:

1===>hello

2===>world

3===>go

4===>is

5===>cool

但是還有一個問題,上面的程序不做改動運行第二次,結果順序就會改變,因為map遍歷出來結果是無序的,這不好控制,也不利於業務邏輯;當業務依賴key次序時,需要引入“sort”包來解決隨機化問題

代碼如下:

package main
import (
    "fmt"
    "sort"
)
func main() {
    m := make(map[string]string)
    m["1"] = "hello"
    m["2"] = "world"
    m["3"] = "go"
    m["4"] = "is"
    m["5"] = "cool"
    sorted_keys := make([]string, 0)
    for k, _ := range m {
        sorted_keys = append(sorted_keys, k)
    }
    sort.Strings(sorted_keys)
    for _, k := range sorted_keys {
        fmt.Printf("%v=====>%v\n", k, m[k])
    }
}

輸出結果是:

1=====>hello

2=====>world

3=====>go

4=====>is

5=====>cool

註意:

輸出的結果運行多次不會改變順序。

但是key的先後順序是按照字母或者數字排列的。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: