English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang function & method

Golang struct

Golang slice & array

Golang string(String)

Golang pointer

Golang interface

Golang concurrency

Golang exception(Error)

Other Golang items

Go Language Pointer Comparison

In Go language, comparing two pointers is allowed. Two pointer values are equal only if they point to the same value in memory or if they are both nil. You can compare pointers using the == and != operators provided by Go language:

1. == operator:If both pointers point to the same variable, this operator returns true. Or if both pointers point to different variables, it returns false.

Syntax:

pointer_1 == pointer_2
package main
import \
func main() {
    val1 := 2345
    val2 := 567
    //Create and initialize a pointer
    var p1 *int
    p1 = &val1
    p2 := &val2
    p3 := &val1
    //Use the == operator to compare pointers
    res1 := &p1 == &p2
    fmt.Println("p1Is the pointer equal to p2Pointer: ", res1)
    res2 := p1 == p2
    fmt.Println("p1Is the pointer equal to p2Pointer: ", res2)
    res3 := p1 == p3
    fmt.Println("p1Is the pointer equal to p3Pointer: ", res3)
    res4 := p2 == p3
    fmt.Println("p2Is the pointer equal to p3Pointer: ", res4)
    res5 := &p3 == &p1
    fmt.Println("p3Is the pointer equal to p1Pointer: ", res5)
}

Output:

p1Is the pointer equal to p2Pointer: false
p1Is the pointer equal to p2Pointer: false
p1Is the pointer equal to p3Pointer: true
p2Is the pointer equal to p3Pointer: false
p3Is the pointer equal to p1Pointer: false

2.!= operator:If both pointers point to the same variable, this operator returns false. Or if both pointers point to different variables, it returns true.

Syntax:

pointer_1 != pointer_2
package main
import \
func main() {
    val1 := 2345
    val2 := 567
    //Create and initialize a pointer
    var p1 *int
    p1 = &val1
    p2 := &val2
    p3 := &val1
    // Use the != operator to compare pointers
    res1 := &p1 != &p2
    fmt.Println("p1Pointer is not equal to p2Is it a pointer: ", res1)
    res2 := p1 != p2
    fmt.Println("p1Pointer is not equal to p2Is it a pointer: ", res2)
    res3 := p1 != p3
    fmt.Println("p1Pointer is not equal to p3Is it a pointer: ", res3)
    res4 := p2 != p3
    fmt.Println("p2Pointer is not equal to p3Is it a pointer: ", res4)
    res5 := &p3 != &p1
    fmt.Println("p3Pointer is not equal to p1Is it a pointer: ", res5)
}

Output:

p1Pointer is not equal to p2Pointer?  true
p1Pointer is not equal to p2Pointer?  true
p1Pointer is not equal to p3Is it a pointer: false
p2Pointer is not equal to p3Pointer?  true
p3Pointer is not equal to p1Pointer?  true