通过&运算符获取nil变量的地址

问题描述 投票:0回答:1

以下代码将通过:

package pointer_learn

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

func TestPointerToNil(t *testing.T) {
    // slice
    var ss []int

    println(&ss)
    println(ss == nil)
    assert.NotNil(t, &ss)
    assert.Nil(t, ss)

    // any
    var x any
    println(&x)
    println(x == nil)

    assert.NotNil(t, &x)
    assert.Nil(t, x)
}

并打印如下内容:

0xc000054748
true
0xc000054738
true

似乎

nil
变量的地址不是
nil

我已经搜索过这个,似乎

&
会创建一个类型为
*T
的指针变量,但我认为它仍然指向nil。

那么打印的地址是什么呢?是 nil 变量的地址,还是指针的值,还是其他什么?

go memory-address
1个回答
0
投票

在 Go 中,像 var ss []int 这样的变量声明会创建一个名为 ss 的切片变量。默认情况下,这是一个切片标头,其中包含指向基础数组第一个元素的指针、切片的长度和容量。但是,当您声明一个切片而不对其进行初始化时,该切片尚未指向任何内存位置,这意味着它是 nil

var ss []int

在上面的示例中,ss是一个切片变量,但它尚未使用任何内存位置进行初始化。结果,ss的地址为0x140001242a0,其值为nil。这表明切片变量存在,但它当前没有指向内存中的任何数组。

ss的地址:0x140001242a0
ss的值:nil

&ss == nil  // Evaluates to false because the address of ss is not nil
ss == nil   // Evaluates to true because ss is not pointing to any memory location

因此:

类似地,在 var x any 的情况下,声明了 any 类型的变量,但未初始化。 x的地址是0x1400010b170,其值为nil

var x any

&x的地址:0x1400010b170
x 的值:nil

这表示变量 x 已声明,但尚未分配任何值或内存位置,因此,它是 nil

© www.soinside.com 2019 - 2024. All rights reserved.