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 5 years have passed since last update.

型変換

Last updated at Posted at 2019-06-05

型変換のことをキャストといいます。
定義されていた変数の型を変換するということ。(コメントにてご指摘いただきました。)

サンプルコード

func main() {
	
	var x int = 1
	xx := float64(x)
	fmt.Printf("%T %v %f\n", xx, xx, xx) //float64 1 1.000000

	var y float64 = 1.2
	yy := int(y)
	fmt.Printf("%T %v %d\n", yy, yy, yy) //int 1 1
	//%d int表示

	var s string = "14"
	// z = int(s) とやると、stringをintに変換できずエラー
	i, _ := strconv.Atoi(s)
	fmt.Printf("%T %v\n", i, i)
	//Atoiは返り値がintとerrorの2つを返すので通常は下記のようにエラーハンドリングをつける。今回はerrを使わないのでそれを明示するアンスコを使ってi, _としてる。
	// var s string = "14"
	// i, err := strconv.Atoi(s)
	// if err != nil {
	// 	fmt.Println("ERROR")
	// }
	// fmt.Printf("%T %v", i, i)

	h := "Break It"
	//fmt.Println(h[0]) //アスキーコード出力される
	fmt.Println(string(h[0])) //B
	//文字列はバイト配列でできているので簡単にキャストできる。strconv使わなくてOK。
}

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

0
0
4

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?