天天看点

go基础学习指针

/*
    指针有两个核心概念:

类型指针:对这个指针类型的数据进行修改,传递数据使用指针,无需拷贝数据。类型指针不能进行偏移和运算。
切片:由指向起始元素的原始指针,元素数量和容量组成
*/
package main

/*
import (
    "fmt"
)
*/
//指针取址
/* func main() {
    i := 1
    s := "qax"
    fmt.Printf("%p %p", &i, &s)
} */

//指针取值
/* func main() {
    name := "wang tang yu"
    ptr := &name
    fmt.Printf("ptr type:%T\n", ptr)
    fmt.Printf("ptr address: %p\n", ptr)
    value := *ptr
    fmt.Printf("value type: %T\n", value)
    fmt.Printf("value: %v\n", value)
} */

// 指针修改值
/* func swap(a, b *int) {
    t := *a
    *a = *b
    *b = t
}

func main() {
    x, y := 1, 2
    swap(&x, &y)
    fmt.Println(x, y)
}
*/

//使用指针获取命令函参数的方法
/* import (
    "flag"
    "fmt"
)

var mode = flag.String("mode", "add ", "process mode")

func main() {
    //定义命令行参数
    flag.Parse()
    fmt.Println(*mode)
}
*/

//创建指针的另一种方法--new()函数
import (
    "fmt"
)

func main() {
    s := new(string)
    *s = "nihao"
    fmt.Printf("s: %v\n", *s)
}