不同的指针是平等的?

Dog*_*Dog 2 pointers go

我试图将2d平面上的某些点表示为整数对.我希望这些点是不可变的(按值传递),但每个点都有一个唯一的标识.为了实现这一点,我创建了一个带有两个ints和a 的结构*string.这很好用:

package main
import "fmt"
func main() {
    s1 := ""
    s2 := ""
    p := Point{1,2,&s1}
    p2 := Point{1,2,&s2}
    fmt.Println(p2==p) // want false
}
type Point struct{X int; Y int; id *string}
Run Code Online (Sandbox Code Playgroud)

$ go run a.go
false
Run Code Online (Sandbox Code Playgroud)

由于string实际上并没有使用任何东西(我只关心两个点是否相同),所以像这样制作唯一引用的规范解决方案似乎是使用指针struct{}代替:

package main
import "fmt"
func main() {
    s1 := struct{}{}
    s2 := struct{}{}
    p := Point{1,2,&s1}
    p2 := Point{1,2,&s2}
    fmt.Println(p2==p) // want false
}
type Point struct{X int; Y int; id *struct{}}
Run Code Online (Sandbox Code Playgroud)

但是,现在两个指针是相等的:

$ go run a.go
true
Run Code Online (Sandbox Code Playgroud)

为什么?这也可以用字符串发生吗?我应该使用UUID吗?

dyo*_*yoo 7

空结构struct{}{}是特殊的.

请参阅:http://golang.org/ref/spec#Size_and_alignment_guarantees,其中说:

如果结构或数组类型不包含大小大于零的字段(或元素),则其大小为零.两个不同的零大小变量在内存中可能具有相同的地址.

你可以在那里放一个字段来获得唯一性.就像是:

package main

import "fmt"

type token struct{ bool }
type Point struct {
    X  int
    Y  int
    id *token
}

func main() {
    p := Point{1, 2, &token{}}
    p2 := Point{1, 2, &token{}}
    fmt.Println(p2 == p) // want false
}
Run Code Online (Sandbox Code Playgroud)