golang 空数组

  • nil
    var ss []student
  • length is zero
    dd := []student{}
  • ff[0] is {"",0}, length is 1
    ff := []student{{}}
package main

import (
	"fmt"
)

func main() {
  // ss: ss is nil
	var ss []student
  // dd's length is zero
	dd := []student{}
  // ff[0] is {"",0}
  ff := []student{{}}
  
	if ss == nil {
		fmt.Printf("ss is nil\n")
	} else {
		fmt.Printf("ss is not nil\n")
	}

	if dd == nil {
		fmt.Printf("dd is nil\n")
	} else if len(dd) == 0 {
		fmt.Printf("dd's length is zero\n")
	} else {
		fmt.Printf("dd[0] is %v, length is %d\n", dd[0], len(dd))
	}
  
  if ff == nil {
		fmt.Printf("ff is nil\n")
	} else if len(ff) == 0 {
		fmt.Printf("ff's length is zero\n")
	} else {
		fmt.Printf("ff[0] is %v, length is %d\n", ff[0], len(ff))
	}
}

type student struct {
	name  string
	class int
}

➜  go run nil_slice/main.go
ss is nil
dd's length is zero
ff[0] is { 0}, length is 1
posted @ 2020-03-20 17:20  leafs99  阅读(5721)  评论(0编辑  收藏  举报