go的 & 和 * 的区别,以及应用场景

& 在go中是直接取地址符
但是在第二项返回的是&{} 而不是0x…地址
这个就不太理解了

package main

import "fmt"

type Test struct {
    name string
}

func main() {
    test := Test{"test"}
    fmt.Println(test)
    //结果{test}

    testa := &Test{"test"}
    fmt.Println(testa)
    //结果 &{test}

    testc := &Test{"test"}
    fmt.Println(*testc)
    //结果 {test}


    testd := &Test{"test"}
    fmt.Println(&testd)
    //结果 0xc000006030
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 4

你要想打印指针类型要用 fmt.Printf

fmt.Printf("value: %p", testa)
3年前 评论

结构体不同变量啊.结构体本身没有分配内存,要实例化了才有内存地址

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!