4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】入門(構造体と関数を紐付ける)

Posted at

Goで構造体と関数を紐付ける方法についてのメモです。

Goで構造体と関数を紐づける方法

Goでは、class内にメソッドを定義できません。
では、どのように構造体ごとの関数を定義するのか?

package main

import "fmt"

type Human struct {
    Name   string
    Age    int
}

func (h Human) addAge(i int) int {
    return h.Age + i
}

func main() {
    // インスタンス生成
    hoge := Human{
        Name:   "hoge",
        Age:    20,
    }

    fmt.Printf("%#v \n", hoge)
    hoge.Age = hoge.addAge(1)
    fmt.Printf("%#v \n", hoge)
}

つまり、構造体と関数の紐付けはこのようになります。

type Human struct {
    Name   string
    Age    int
}

func (h Human) addAge(i int) int {
    return h.Age + i
}

一般化すると、こうですね。

type 構造体 struct {
    // フィールド定義
}

func (変数名 構造体) 関数名(変数名 )  {
    // do something
    return 
}

(変数名 構造体)を関数の前に加えるだけで、構造体と関数が紐づけられます。
ここで定義した関数は構造体が作成されないと使用できません。
このようにして、構造体ごとに関数を定義することができます。

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?