切片分配后,为什么内存地址会更改

时间:2019-11-11 01:59:49

标签: go

有两个我不明白的问题。
第一个是将一个片变量分配给另一个变量,并且发现新变量的地址与该变量的地址不一致。我的理解是slice共享内存,并且根据原理它们的地址是相同的。

然后是秒,当slice变量的容量不足时,追加操作后内存地址不会更改。它应该根据原理进行更改,因为在容量不足时将重新分配内存地址。

感谢您的评论。

0xc04204c3a0
0xc04204c3e0
0xc04204c3e0
[1 2 3]
[1 2 3 0]

运行结果是:

// index.js

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration : true
    
    }
  })

  // and load the index.html of the app.
  mainWindow.loadURL(`${__dirname}/index.html`)

  // This is the actual solution
mainWindow.webContents.on("new-window", function(event, url) {
  event.preventDefault();
  shell.openExternal(url);
});

2 个答案:

答案 0 :(得分:4)

切片值包含一个指向后备数组,长度和容量的指针。有关详细信息,请参见Go Slices: usage and internals

以下是有关问题代码的一些注释:

var a = []int{1, 2, 3}

// Print address of variable a
fmt.Printf("%p\n", &a)

b := a

// Print address of variable b. The variable a and b
// have different addresses.
fmt.Printf("%p\n", &b)

b = append(b, 0)

// Print address of variable b. Append did not change
// the address of the variable b.
fmt.Printf("%p\n", &b)

打印第一个slice元素的地址以获得所需的结果。

var a = []int{1, 2, 3}

// Print address of a's first element
fmt.Printf("%p\n", &a[0])

b := a

// Print address of b's first element. This prints
// same value as previous because a and b share a backing
// array.
fmt.Printf("%p\n", &b[0])

b = append(b, 0)

// Print address of b's first element. This prints a 
// different value from previous because append allocated
// a new backing array.
fmt.Printf("%p\n", &b[0])

答案 1 :(得分:1)

// create a new slice struct which contains length, capacity and the underlying array. 
// len(a)=3, cap(a)=3
var a = []int{1,2,3}

// `&a` means the pointer to slice struct
fmt.Printf("%p\n",&a)

// `b` is another newly created variable of slice struct, so `&b` differs from `&a`, 
// but they share the same underlying array.
// len(b)=3, cap(b)=3
b := a

// the underlying array of `b` has been extended, and been newly allocated.
// but the pointer of `b` remains.
// len(b)=4, cap(b)=6
b = append(b, 0)

希望这些评论对您有帮助