LoginSignup
0
0

More than 3 years have passed since last update.

競プロで使うための GO 入門 ~型変換~

Posted at

Index

型変換

Go は、別の型同士の演算・代入・比較が行えないため、型変換を頻繁に利用する。

int <-> float64

package main

import (
    "fmt"
)

func main() {

    var i int = 5
    var f float64 = 5.9

    // float64をintへキャスト(小数点切り捨て)
    fmt.Println(i + int(f)) // ->10

    //intをfloat64へキャスト
    fmt.Println(float64(i) + f) // ->10.9
}

数値 <-> 文字

"strconv"パッケージを使用する

package main

import (
    "fmt"
    "strconv" // strconv
)

func main() {

    var s_1 string = "12"
    var s_2 string = "34"
    var i_1 int
    var i_2 int

    i_1, _ = strconv.Atoi(s_1)
    i_2, _ = strconv.Atoi(s_2)

    fmt.Println(i_1 + i_2) // ->46

    s_1 = strconv.Itoa(i_2)
    s_2 = strconv.Itoa(i_1)

    fmt.Println(s_1 + s_2) // ->3412
}

文字列 <-> 論理型

package main

import (
    "fmt"
    "strconv" // strconv
)

func main() {

    var s string = "true"
    var b bool
    b, _ = strconv.ParseBool(s)
    fmt.Println(b) // ->true

    s= strconv.FormatBool(b)
    fmt.Println(s) // ->"false"
}
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