# Golang中如何比较指针？解析和示例

2021年3月29日16:57:50 发表评论 1,858 次浏览

1. ==运算符：如果两个指针都指向同一变量, 则此运算符返回true。或如果两个指针都指向不同的变量, 则返回false。

``pointer_1 == pointer_2``

``````// Go program to illustrate the
// concept of comparing two pointers
package main

import "fmt"

func main() {

val1 := 2345
val2 := 567

// Creating and initializing pointers
var p1 * int
p1 = &val1
p2 := &val2
p3 := &val1

// Comparing pointers
// with each other
// Using == operator
res1 := &p1 == &p2
fmt.Println( "Is p1 pointer is equal to p2 pointer: " , res1)

res2 := p1 == p2
fmt.Println( "Is p1 pointer is equal to p2 pointer: " , res2)

res3 := p1 == p3
fmt.Println( "Is p1 pointer is equal to p3 pointer: " , res3)

res4 := p2 == p3
fmt.Println( "Is p2 pointer is equal to p3 pointer: " , res4)

res5 := &p3 == &p1
fmt.Println( "Is p3 pointer is equal to p1 pointer: " , res5)
}``````

``````Is p1 pointer is equal to p2 pointer:  false
Is p1 pointer is equal to p2 pointer:  false
Is p1 pointer is equal to p3 pointer:  true
Is p2 pointer is equal to p3 pointer:  false
Is p3 pointer is equal to p1 pointer:  false``````

2.!=运算符：如果两个指针都指向同一变量, 则此运算符返回false。或如果两个指针都指向不同的变量, 则返回true。

``pointer_1 != pointer_2``

``````// Go program to illustrate the
// concept of comparing two pointers
package main

import "fmt"

func main() {

val1 := 2345
val2 := 567

// Creating and initializing pointers
var p1 * int
p1 = &val1
p2 := &val2
p3 := &val1

// Comparing pointers
// with each other
// Using != operator
res1 := &p1 != &p2
fmt.Println( "Is p1 pointer not equal to p2 pointer: " , res1)

res2 := p1 != p2
fmt.Println( "Is p1 pointer not equal to p2 pointer: " , res2)

res3 := p1 != p3
fmt.Println( "Is p1 pointer not equal to p3 pointer: " , res3)

res4 := p2 != p3
fmt.Println( "Is p2 pointer not equal to p3 pointer: " , res4)

res5 := &p3 != &p1
fmt.Println( "Is p3 pointer not equal to p1 pointer: " , res5)
}``````

``````Is p1 pointer not equal to p2 pointer:  true
Is p1 pointer not equal to p2 pointer:  true
Is p1 pointer not equal to p3 pointer:  false
Is p2 pointer not equal to p3 pointer:  true
Is p3 pointer not equal to p1 pointer:  true``````