Go语言编程入门超级指南

2020-01-28 12:01:04王冬梅

    var a [5]int
    fmt.Println("Array未初始化: ", a)

    a[1] = 10
    a[3] = 20
    fmt.Println("Array赋值: ", a)

    b := []int{0, 1, 2, 3, 4, 5}
    fmt.Println("Array初始化: ", b)

    var c [2][3]int
    for i := 0; i < 2; i++ {
        for j := 0; j < 3; j++ {
            c[i][j] = i + j
        }
    }
    fmt.Println("Array二维: ", c)

    d := b[2:4] // b[3,4]
    e := b[:4]  // b[1,2,3,4]
    f := b[2:]  // b[3,4,5]
    fmt.Println("Array切片:", d, e, f)
}

func testMap() {
    m := make(map[string]int)

    m["one"] = 1
    m["two"] = 2
    m["three"] = 3
    fmt.Printf("Map哈希表:%v,长度[%d]n", m, len(m))

    delete(m, "two")
    fmt.Printf("Map删除元素后:%v,长度[%d]n", m, len(m))

    m["four"] = 4
    m["five"] = 5
    fmt.Println("Map打印:")
    for key, val := range m {
        fmt.Printf("t%s => %dn", key, val)
    }
    fmt.Println()
}

3.5 指针和内存分配

Golang中可以使用指针,并提供了两种内存分配机制:

new:分配长度为0的空白内存,返回类型T*。
make:仅用于 切片、map、chan消息管道,返回类型T而不是指针。

package main

import "fmt"

/**
 * 整数i=[10],指针pInt=[0x184000c0],指针指向*pInt=[10]
 * 整数i=[3],指针pInt=[0x184000c0],指针指向*pInt=[3]
 * 整数i=[5],指针pInt=[0x184000c0],指针指向*pInt=[5]
 *
 * Wild的数组指针: <nil>
 * Wild的数组指针==nil[true]
 *
 * New分配的数组指针: &[]
 * New分配的数组指针[0x18443010],长度[0]
 * New分配的数组指针==nil[false]
 * New分配的数组指针Make后: &[0 0 0 0 0 0 0 0 0 0]
 * New分配的数组元素[3]: 23
 *
 * Make分配的数组引用: [0 0 0 0 0 0 0 0 0 0]
 */
func main() {
    testPointer()
    testMemAllocate()
}

func testPointer() {
    var i int = 10;
    var pInt *int = &i;
    fmt.Printf("整数i=[%d],指针pInt=[%p],指针指向*pInt=[%d]n",