본문 바로가기
Go

[Go] Pointer

by llHoYall 2021. 10. 11.

Pointer is a type that has a memory address as a value.

Pointer Variable

Defining a pointer variable uses a * symbol in front of the type.

* symbol is also used to access the value of a pointer variable.

And & symbol means the address of a variable.

package main

import "fmt"

func main() {
  var pNum *int
  num := 7

  // Assign address to pointer
  pNum = &num

  // Access to pointer
  fmt.Println(*pNum) // 7

  // Assign value to pointer
  *pNum = 3

  // Access to pointer
  fmt.Println(*pNum) // 3
}

The default value of the pointer variable is nil.

Pass-by-Pointer

Pass-by-Value is the default by Go.

In this case, copying of the value occurs, so as to slow. In addition, if you want to change the value of an argument, it will not be passed to the caller.

If you use a pointer as a function's parameter, it will just copy the address of the argument, therefore it is fast. And it can pass the changed value to its caller.

func func1(arg int) {
  arg = 3
}

func func2(arg *int) {
  *arg = 5
}

func main() {
  num := 7

  func1(num)
  fmt.Println(num) // 7

  func2(&num)
  fmt.Println(num) // 5
}

Pointer Variable with Structure

It is possible to create a structure without a structure variable and assign its address as an initial value.

type person struct {
  name string
  age  int
}

func main() {
  var kim *person = &person{"hoya", 18}
  fmt.Println(kim.name, kim.age)
  // hoya 18
}

We can easily define a pointer variable using the built-in function new().

park := new(person)

new() function returns the address of the zero-initialized memory space.

Garbage Collector

Go has garbage collector like Java, Python.

Therefore, pointer variables that are no longer used are released by GC.

Stack Memory and Heap Memory

Most of the programming language uses stack and heap memory.

And its usage is defined by the language specification.

But, Go determines which memory to use through escape analysis in run-time.

In addition, stack memory is not a fixed-sized memory in Go. It is a growing dynamic memory pool.

'Go' 카테고리의 다른 글

[Go] Package  (0) 2021.10.16
[Go] Rune and String  (0) 2021.10.16
[Go] Structure  (0) 2021.10.11
[Go] Array  (0) 2021.10.10
[Go] Control Flow  (0) 2021.10.10

댓글