簡體   English   中英

Go結構指針不是唯一的

[英]Go struct pointers not unique

我正在嘗試創建元素圖。 我想使用指針而不是整數作為鍵。 問題是...我不斷得到相同的指針。 無論我創建多少次。 為什么是這樣? 如何獲得真實的指針,如果可能的話,不使用不安全的軟件包。

package main

import (
    "fmt"
)

type Thingy struct{}

var things map[*Thingy]int

func main() {
    things = make(map[*Thingy]int)

    thing1 := new(Thingy)
    tracePointer("thing1", thing1)
    things[thing1] = 1

    thing2 := new(Thingy)
    tracePointer("thing2", thing2)
    things[thing2] = 2

    thing3 := &Thingy{}
    tracePointer("thing3", thing3)
    things[thing3] = 3

    fmt.Printf("Amount of things: %d\n", len(things))
}

func tracePointer(identifier string, obj interface{}) {
    fmt.Printf("%s pointer: %p\n", identifier, obj)
}

輸出繼電器:

thing1 pointer: 0x546570
thing2 pointer: 0x546570
thing3 pointer: 0x546570
Amount of things: 1

struct{}是一種特殊情況,它始終使用0個字節的內存,並且始終具有相同的地址。

如果只需要一個虛擬指針,則可以使用type Thingy byte

thing1 pointer: 0x10328000
thing2 pointer: 0x10328020
thing3 pointer: 0x10328021
Amount of things: 3

操場

//編輯

正如James Henstridge在評論中指出的那樣,如果struct{}的地址位於更大的struct中,則它們的地址會更改。

http://play.golang.org/p/51_PhqDNhk

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM