0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【A Tour of Go】Go言語のポインタをわかりやすく解説!

Posted at

先日、Go言語のインターンに参加する機会がありました。そのため、その復習も兼ねて、Go公式チュートリアルの「A Tour of Go」に取り組んでいます。

今回はその中でも「More types: structs, slices, and maps.」の章を進める中で、ポインタの仕組みについて、分かりにくいと感じた部分を中心にまとめました。

間違いや勘違いがあればぜひコメントで教えていただけると嬉しいです🙇
Go初学者の方の参考になれば幸いです!

Pointers

ポインタとは、「ある変数がメモリ上のどこにあるか(住所)」を表す値です。
今回はポインタを家、住所に例えてコード例を用いながら解説します。

ポインタを用いたコードの例

package main

import "fmt"

func main() {
    x := 42         // x は int 型
    p := &x         // pにxのアドレスを代入すると、pはintのポインタ型 になる
    
    fmt.Println(x)  // 42(普通に出力される)
    fmt.Println(p)  // 0xc000014088(xのメモリアドレス)
    fmt.Println(*p) // 42(ポインタが指す先の値を出力)
}

このコードをわかりやすく解説します!

        ~~~~~~~~~
       /         \    
      /___________\   
     |             |   
     |   x = 42    |   x = 42という家がある(実体)
     |_____________|  
           ↑
    ポインタ変数pを辿って、x=42にアクセスできる
           ↑
    &xで xの住所0xc000014088を取得する

x = 42 という「家」がある。
&x で「この家の住所」を取得する。
p は「その家の住所を記録したメモ」。
*p を使うと、住所をたどって「家の中にある値(42)」を取り出せる。

Goではポインタを比較的シンプルに使うことができます。
わからないと思っていた人も、この記事で理解してくれたらうれしいです!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?