[Golang] Pointer

2021-10-25 hit count image

Let's see how to use Pointer for accessing the variable memory address in Golang.

Outline

In this blog post, I will show you how to use Pointer to manage the variable memory address in Golang. You can see the full source code of this blog post on the link below.

Pointer

The pointer is a type to have a memory address for the value. In Golang, you can define the pointer like the below.

var VARIABLE_NAME *TYPE
var p *int

When you define the variable like the above, you can store the another variable’s memory address by using the & operator.

var a int
var p *int
p = &a
*p = 20

At this time, the variable and pointer should be same type. If the type is different, the compile error will occur.

To check how to use the pointer in Golang, create the main.go file and modify it like the below.

package main

import "fmt"

func main() {
  var a int = 10
  var p *int

  fmt.Println(a)

  p = &a
  fmt.Printf("%v\n", &a)
  fmt.Printf("%v\n", p)

  *p = 20
  fmt.Println(a)
  fmt.Println(*p)
}

When you execute the above code, you can see the result like the below.

# go run main.go
10
0xc00001a0e8
0xc00001a0e8
20
20

As you can see the result, the variable a and the pointer p are same memory address, and the pointer value is changed, the variable a is also changed to same value.

Default value of Pointer

In Golang, if you define a variable and don’t initialize it, the default value of the variable type is assigned. However, the pointer variable that is not initialized will be assigned nil.

To check this, modify the main.go file like the below.

package main

import "fmt"

func main() {
  var p *int

  fmt.Println(p)
}

When you execute the code above, you can see the following result.

# go run main.go
<nil>

So, when you use the pointer variable, you can check the pointer is initialized or not like the below.

var p *int
if p != nil {
  fmt.Println("Assigned")
}

Pointer in function

In Golang, you can use the pointer like the below.

package main

import "fmt"

type Data struct {
  value int
  data  [200]int
}

func ChangeData(arg Data) {
  arg.value = 100
  arg.data[100] = 999
}

func ChangePData(arg *Data) {
  arg.value = 100
  arg.data[100] = 999
}

func main() {
  var data Data
  ChangeData(data)
  fmt.Printf("value = %d\n", data.value)
  fmt.Printf("data[100] = %d\n", data.data[100])

  ChangePData(&data)
  fmt.Printf("value = %d\n", data.value)
  fmt.Printf("data[100] = %d\n", data.data[100])
}

When you execute the code, you can see the result like the below.

# go run main.go
value = 0
data[100] = 0
value = 100
data[100] = 999

When you use the pointer to the parameter, and you can update the value of the variable directly in the function.

Initialize struct pointer

In Golang, you can initialize the struct pointer like the below.

package main

import "fmt"

type Data struct {
  value int
  data  [200]int
}

func main() {
  var data Data
  var p1 *Data = &data
  var p2 *Data = &Data{}

  fmt.Println(*p1)
  fmt.Println(*p2)
}

Instance

The data that is assigned to the memory is called instance.

new built-in function

You can use the new built-in function to create the instance of the struct like the below.

p1 := &Data{}
var p2 = new(Data)

Here, the p1 and p2 is the pointer variables and the type is *Data.

When the instacne disappears

Golang also has the Garbage collector, and when all variables that refer to the instance are deleted, the instance will be deleted automatically.

  • Dangling Pointer: when the pointer refers to the memory that is no longer valid, the Dangling Pointer error occurs.
package main

import "fmt"

type User struct {
  Name string
  Age  int
}

func NewUser(name string, age int) *User {
  var u = User{name, age}
  return &u
}

func main() {
  userPointer := NewUser("John", 20)
  fmt.Println(userPointer)
  fmt.Println(userPointer.Age)
  fmt.Println(userPointer.Name)
}

In C, C++, the variable u exists in the NewUser function, so when the function call ends(}), the variable is deleted. Therefore, the function retuns the deleted variable address, so the userPointer refers to the variable address that is no longer valid, and the Dangling Pointer error occurs.

func NewUser(name string, age int) *User {
  var u = User{name, age}
  return &u
}

However, in Golang, the variable userPointer in the main function refers to the variable u memory address, so the u variable instance is not deleted. So, Dangling Pointer error does not occur in Golang. Golang uses Escape Analysis to detect the variable is referred by outside of the function or not, and stores it to the heap memory, so the error doesn’t occur.

Completed

Done! we’ve seen how to use the pointer to refer the variable memory and use it in Golang. Here is the summary.

  • An instance is an object of data created in memory, and a pointer can be used to point to the instance.
  • A function can have pointer parameters and the function can modify the value of the instance directly.
  • When the instance is no longer valid, Garbage collector deletes it automatically.

In Golang, Pointer variables are used a lot, so keep this in mind!

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

Posts