LoginSignup
0
0

More than 3 years have passed since last update.

go修行9日目 ポインタとか

Last updated at Posted at 2020-06-22

ポインタ型

  • &nでポインタのアドレスを指定
  • *intで指定したアドレスの中身を取得

package main

import "fmt"

func main() {
    var n int = 100
    fmt.Println(n)
    fmt.Println(&n)

    // pはポインタ型
    var p *int = &n

    fmt.Println(p)

    fmt.Println(*p)
}
100
0xc000104030
0xc000104030
100

newとmake


package main

import "fmt"

func main(){
    // メモリのアドレスを確保している
    var p *int = new(int)
    fmt.Println(p)

    // メモリのアドレスは確保していないのでnil
    var p2 *int
    fmt.Println(p2)
}
0xc0000120b8
<nil>

struct


package main

import "fmt"

type Vertex struct{
    X,  Y int
    S string
}

func main() {
    // XとYを指定して数値を入れる
    v := Vertex{X: 1, Y:2}
    fmt.Println(v)
    fmt.Println(v.X, v.Y)
    v.X = 100
    fmt.Println(v.X, v.Y)

    // Xだけ入れるとYは0扱い
    v2 := Vertex{X: 1}
    fmt.Println(v2)

    // XやYを指定しない場合  文字列も含む
    v3 := Vertex{1,2,"test"}
    fmt.Println(v3)

    // なにも入れない場合はデフォルトの0か空文字が入る
    v4 := Vertex{}
    fmt.Println(v4)
}
{1 2 }
1 2
100 2
{1 0 }
{1 2 test}
{0 0 }

コンストラクタ

???


package main

import "fmt"

type Vertex struct{
    //小文字にするとx.yを書き換えられる
    x, y int
}

func (v Vertex) Area() int{
    return v.x * v.y
}

func (v *Vertex) Scale(i int){
    v.x = v.x * i
    v.y = v.y * i
}

func New(x, y int) *Vertex{
    return &Vertex{x, y}
}

func main(){
    v := Vertex{3, 4}
    v.Scale(10)
    fmt.Println(v.Area())
}
1200
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