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?

More than 3 years have passed since last update.

【Golang】interface②タイプアサーション

Posted at

#【Golang】interface②タイプアサーション
Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main 

import (
	"fmt"
)

//interface2の使い方
func do(i interface{}){
	//1
	/*
		//int型に直す。正しければ復元する
		//タイプアサーション 
		ii := i.(int)
		// i = ii * 2
		ii *= 2
		fmt.Println(ii)

		//str型に直す
		ss := i.(string)
		fmt.Println(ss + "!")
	*/

	//2
	//interfaceをtype毎に条件分岐 vを変換
	//スイッチタイプ文
	//switch v := i.(type) はセットで覚える(型アサーション)
	switch v := i.(type) {
	case int:
		fmt.Println(v * 2)
	case string:
		fmt.Println(v + "!")
	default:
		fmt.Printf("%T\n", v)
	}
}

func main() {
	//1
	//まだint型でない interface型
	var i interface{} = 10
	var s interface{} = "Mike"

	//2
	//いろんな型で実行
	do(i)
	//>>20
	do(s)
	//>>Mike!
	do(true)
	//>>bool
	


	//3
	//タイプアサーション、コンバージョン
	var i2 int = 10
	//タイプコンバージョンは書き換える
	ii := float64(10)
	fmt.Println(i2, ii)
	//>>10 10

	//タイプアサーション
	//interfaceの場合の変換
	//var i interface{} = 10
	//i.(int)で変換する

}
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?