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

☑本記事の内容
  • non-structのメソッド
  • インターフェース
  • タイプアサーション
参考資料:現役シリコンバレーエンジニアが教えるGo入門 + 応用でビットコインのシストレFintechアプリの開発

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

✔non-structのメソッドの目次

基本的なこと

  • struct以外でもメソッドは使用できる
  • あまり使わないので頭の片隅にあるくらいでOK
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
  • intの場合だとキャストをしないとエラーになる
  • 関数となっているためエラーが発生する
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言語入門 -インターフェース-

✔インターフェースの目次

基本的なこと

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

値を書き換えたい場合

  • ポインタを使用する
  • アスタリスク(*)を使用して、&をつけアドレスを渡す
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言語入門 -タイプアサーション-

✔タイプアサーションの目次

基本的なこと

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

import "fmt"

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

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

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

  • interface{}に複数の型を入れた際にはswitch type文を使用する
  • typeのタイプアサーションはswitchとセットでしか使用できない
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言語入門⑪へ

目次

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

ABOUT US
サカイザ
機械設計→技術営業→SEと転職し、
現在フリーランスエンジニア
北海道出身東京在住
現在、Go案件を受注中
扱えるスキルGo,GCP,Java,AWS,SQL,Python,PHP,etc...
合同会社エンブリオ 代表社員