Go 入門

Go言語入門⑫ ~non-structのメソッド・インターフェース・タイプアサーション~

[box class="blue_box" title="☑本記事の内容"]

  • non-structのメソッド
  • インターフェース
  • タイプアサーション

[/box]
参考資料:現役シリコンバレーエンジニアが教えるGo入門 + 応用でビットコインのシストレFintechアプリの開発
[box class="glay_box" title="Contents"]

  1. Go言語入門 -non-structのメソッド-
  2. Go言語入門 -インターフェース-
  3. Go言語入門 -タイプアサーション-

[/box]

Go言語入門 -non-structのメソッド-

[box class="yellow_box" title="✔non-structのメソッドの目次"]

[/box]

基本的なこと

[box class="glay_box"]

  • struct以外でもメソッドは使用できる
  • あまり使わないので頭の片隅にあるくらいでOK

[/box]

package main

import "fmt"

type MyInt int

func (i MyInt) Double() int {
	return int(i * 2)
}

func main() {
	myInt := MyInt(10)
	fmt.Println(myInt.Double())
}
(結果)
20

[box class="glay_box"]

  • intの場合だとキャストをしないとエラーになる
  • 関数となっているためエラーが発生する

[/box]

package main

import "fmt"

type MyInt int

func (i MyInt) Double() int {
	fmt.Printf("%T %v\n", i, i)
	fmt.Printf("%T %v\n", 1, 1)
	return int(i * 2)
}

func main() {
	myInt := MyInt(10)
	fmt.Println(myInt.Double())
}
(結果)
main.MyInt 10
int 1
20

Go言語入門 -インターフェース-

[box class="yellow_box" title="✔インターフェースの目次"]

[/box]

基本的なこと

[box class="glay_box"]

  • インターフェースはメソッド名のみを記載する
  • 実装は別の関数を使って書く
  • 型みたいな印象

[/box]

package main

import "fmt"

type Human interface {
	Say()
}

type Person struct {
	Name string
}

func (p Person) Say() {
	fmt.Println(p.Name)
}

func main() {
	var mike Human = Person{"Mike"}
	mike.Say()

}
(結果)
Mike

値を書き換えたい場合

[box class="glay_box"]

  • ポインタを使用する
  • アスタリスク(*)を使用して、&をつけアドレスを渡す

[/box]

package main

import "fmt"

type Human interface {
	Say()
}

type Person struct {
	Name string
}

func (p *Person) Say() {
	p.Name = "Mr." + p.Name
	fmt.Println(p.Name)
}

func main() {
	var mike Human = &Person{"Mike"}
	mike.Say()

}
(結果)
Mr.Mike

Go言語入門 -タイプアサーション-

[box class="yellow_box" title="✔タイプアサーションの目次"]

[/box]

基本的なこと

[box class="glay_box"]

  • interface{}だと複数の異なる型でも入れることが出来る
  • 出力する時はそのままだとエラーになるので、タイプアサーションをする
  • i.(int)のように後ろに型をつける

[/box]

package main

import "fmt"

func do(i interface{}) {
	ii := i.(int)
	ii *= 2
	fmt.Println(ii)
}

func main() {
	do(10)
}
(結果)
20

複数の型を入れた際の出力

[box class="glay_box"]

  • interface{}に複数の型を入れた際にはswitch type文を使用する
  • typeのタイプアサーションはswitchとセットでしか使用できない

[/box]

package main

import "fmt"

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Println(v * 2)
	case string:
		fmt.Println(v + "!")
	default:
		fmt.Printf("I don't know %T\n", v)
	}
}

func main() {
	do(10)
	do("Mike")
	do(true)
}
(結果)
20
Mike!
I don't know bool

Go言語入門⑬へ ≫

≪ Go言語入門⑪へ

目次

-Go, 入門