Golang Basic syntax-Advanced data type (3)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang Basic syntax-Advanced data type (3)

This article mainly introduces the Golang built-in data type array, slice, map. These kinds of data types are very common in everyday use.

Array

The
definition syntax is as follows:
var arr [N]type
Where Arr is the name (identifier) of the array variable, [n]type indicates that the array is of type N-length array (type can be any base type, or it can be any custom type)
//实例演示var arr [10]int //定义一个长度为10的 int 类型的数组arr[0] = 42 //array 数组下标是从0开始的,给数组第一个元素赋值42arr[1] = 13//给数组第二个元素赋值13//打印数组第一个元素fmt.Printf("数组 arr 第一个元素是 %d\n", arr[0])//打印数组最后一个元素,arr[9]因为没有初始化,输出 int 类型的零值 0fmt.Printf("数组 arr 最后一个元素是 %d\n", arr[9])
when defining an array, you can see [n]type as a complete type, for example, [3]int and [4]int can be thought of as different data types, and the length of the array is not modifiable.

When the data of an array type is passed as a function parameter, the copy (copy value) of the array is passed instead of the reference

/** * 数组是值传递而非引用传递 */func test(arr [4]int) int {    var sum int    for i, v := range arr {        sum = sum + v        arr[i] = sum    }    //打印结果是[1 3 7 12]    fmt.Printf("%+v\n", arr)    return sum}func main() {    arr := [4]int{1, 2, 4, 5}    //打印结果 12    fmt.Printf("%d\n", test(arr))    //打印结果[1 2 4 5],把 arr 传递给 test函数,且函数内修改了数组,没有影响原数组,证明数组在函数参数中是传递 copy而不是引用    fmt.Printf("%v\n", arr)}
//快捷方式定义数组arr := [3]int{1, 2, 3}//使用 ...替代长度让编译器自动计算数组的长度arr1 := [...]int{3, 5, 5}//二维数组darr :=[2][3]int{[3]int{1,2,3}, [3]int{33,33,33}}darr1 := [2][3]int{{2, 3, 4}, {1, 3, 4}}

Slice (slices or variable-length arrays)

At the beginning of the array, it is necessary to know its length, but many times we cannot determine the size of the array, and we need a "dynamic array". Slice in Golang provides us with this possibility.

the definition of slice is very similar to the array, except that you don't have to set n
Syntax var slice[]int

Description: The above syntax defines an int type of slice,

//实例说明//定义一个byte 类型的 slice,注意 byte 是uint8的别名,byte类型的 slice中,如果元素赋值为汉字超出 uint8的范围就会报错slice := []byte{'a', 'b', 'c'}
Slice can redefine a slice from an already existing array (array) or slice (slice), the syntax format is [i:j], I is the starting index, and J is the index of the end, but the final slice does not contain the element J
//实例演示var ar = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}var a, b []byte//变量a 实际上的内容为 c,d,e 且 a 和 ar 共用底层数据a = ar[2:5]//变量 b 实际上的内容为 d,e 且 b 和 ar 共用底层数据b = ar[3:5]//思考如下结果是什么?ar[4] = 'x'fmt.Printf("%c\n", ar[4])//显然是 xfmt.Printf("%c\n", a[2])//a[2]实际上指向的是 ar[4],结果是 xfmt.Printf("%c\n", b[1])//b[1]实际上指向的是 ar[4],结果是 x
Ar[:n] equivalent to ar[0:n]
Ar[n:] equivalent to Ar[n:len (AR)]
ar[:] equivalent to Ar[0:len (AR)]
//实例演示var arr = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}var aSlice, bSlie []byteaSlice = arr[:3] // a b caSlice = arr[5:] //f g h i jaSlice = arr[:] // a b c d e f g h i jaSlice = arr[3:7] // d e f g, 长度 len=4, 容量 cap=10-3bSlice = aSlice[1:3] // e f

Slice are reference types, so any change will affect other slice or arrays that point to the same slice.

Slice is similar to a struct, and includes the following three parts

  • A pointer: The starting address of the slice point
  • Length of slice int type
  • capacity int type of slice

There are some built-in functions to manipulate slice

    • Len gets the length of the slice
    • Cap gets the maximum capacity of the slice
    • Append append one or more slice to slice
    • Copy copies all elements of a slice to another slice, returning the number of copied elements

Map

Map is a key-value pair data structure, similar to a dictionary in Python. The definition syntax is as follows:

Map[keytype]valuetype

Slice index can only be int , in the map key can be int string waiting for any type you want

The example shows the following

//使用 string 类型的 key,int类型的 value,可以使用 make 初始化var numbers map[string]int//定义并且使用 make 初始化numbers := make(map[string]int)//初始化后可以赋值numbers["one"] = 1numbers["two"] = 2numbers["three"] = 3//获取 map 某个 key 的 valuefmt.Println(numbers["three"])

Map needs to be noted

  • The map is unordered, each time the result of the print display may be different, you can only use key to get the value
  • Map does not have a fixed length, it is a type of reference variable
  • The Len function can be used to get the length of a map, returning how many keys the map has
  • It is very easy to change the value of map by key just by using m["k"] = 1 a similar syntax modification
//定义并且初始化 maprating := map[string]float32 {"C":5, "Go":4.5, "PHP":100}javaRating, ok := rating["Java"]if ok {    //do something}else{    //do something}//删除 map 中的某个键值对delete(rating, "C")m := make(map[string]string)m["hello"] = "world"m1 := mm1["hello"] = "girl" //m["hello"]的值也是 girl,因为底层指向数据一致

The difference between make and new

Make is a method built into go that allocates memory for built-in types such as Map,slice,channel, which new can assign to all types
New (t) assigns 0 value memory to T, and returns the memory address of the 0 value, in fact, is *t, in more detail, is to return a pointer, the pointer to the T 0 value

new Returns a pointer

Make is used primarily for slice map channel, returning the initialized T. The reason is that the data at the bottom of the map slice channel must be initialized to point to them. For example, slice includes a pointer that actually points to a different structure (with pointer-length capacity), slice is nil before the data is initialized, so Slice,map,channel uses make to assign the appropriate initial value to their underlying data structure

Make
returns a value other than 0
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.