Section I, Go study notes - declare and initialize

Variable declaration

  1. var variable name = type expression
  2. var Variable Name Type
  3. var variable name 1, variable name 2, Type 3 Variable Name
  4. var variable name 1, variable name 2, 3 = variable name expression 1, expression 2, expression 3

Short variable declaration

  1. Variable name: = expression
  2. 1 variable name, variable name 2: = expression 1, expression 2

Pointer variable declaration

  1. was int * p
  2. var p = & T, p: = & T // T represents a variable name
  3. p := new(type)、var p = new(type)

First, declare and initialize an array

  1. var array [5]int // specified length
  2. array := [5]int{10, 20, 30, 40, 50} // specified length and literals
  3. array := [...]int{10, 20, 30, 40, 50} // compiler automatically calculate the length
  4. array := [5]int{1: 10, 2: 20} // the specified array length and partial value

Two, slice declare and initialize

  1. slice := make([]string, 5)// use makethe specified length
  2. slice := make([]int, 3, 5) // specified length and capacity, length> = Capacity
  3. slice := []int{10, 20, 30} // use literal
  4. slice := []string{99: ""}Use index declare and specify the initialization value

Third, create a nilslice

  • slice were [] int

Fourth, create a slice

  • slice := make([]int, 0) // Create an empty integer make use sliced
  • slice := []int{} // Create an empty literal use slice sliced ​​integer

V. mapping declare and initialize

// 1、使用"make"申明
// 创建一个映射,键的类型是 string,值的类型是 int
dict := make(map[string]int) 
//2、使用字面量申明
// 创建一个映射,键和值的类型都是 string
// 使用两个键值对初始化映射
dict := map[string]string{"Red": "#da1337", "Orange": "#e95a22"}
//3、声明一个存储字符串切片的映射
dict := map[int][]string{}
//4、声明一个空映射
dict := map[string]int{}

Sixth, declare a nilmap

// 通过声明映射创建一个 nil 映射
var colors map[string]string
Published 12 original articles · won praise 0 · Views 467

Guess you like

Origin blog.csdn.net/w0iloveyou/article/details/104559612