LoginSignup
0
0

More than 1 year has passed since last update.

【自己学習】Go言語を学ぶ(5)

Posted at

公式チュートリアルから基本を学ぶ
https://go-tour-jp.appspot.com/list

Zero values(ゼロ値)

  • 変数に初期値を与えずに宣言すると、ゼロ値( zero value )が与えられます。

  • 初期値

    • 数値型(int,floatなど): 0
    • bool型: false
    • string型: "" (空文字列( empty string ))

サンプルコード

package main

import "fmt"

func main() {
  var i int
  var f float64
  var b bool
  var s string
  fmt.Printf("%v %v %v %q\n", i, f, b, s)
}

結果:0 0 false ""

Type conversions(型変換)

サンプルコード
math.Sqrtを使って各値の平方根を計算する

package main

import (
  "fmt"
  "math"
)

func main() {
  var x, y int = 3, 4
  var f float64 = math.Sqrt(float64(x*x + y*y))
  var z uint = uint(f)
  fmt.Println(x, y, z)
}

結果:3 4 5

Type inference(型推論)

明示的な型を指定せずに変数を宣言する場合( := や var = のいずれか)、変数の型は右側の変数から型推論されます。

var i int
j := i // int型

i := 42           // int
f := 3.142        // float64
g := 0.867 + 0.5i // complex128

サンプルコード

package main

import "fmt"

func main() {
  i := 42           // int
  f := 3.142        // float64
  g := 0.867 + 0.5i // complex128
  fmt.Printf("i is of type %T\n", i)
  fmt.Printf("f is of type %T\n", f)
  fmt.Printf("g is of type %T\n", g)
}

結果

i is of type int
f is of type float64
g is of type complex128

Constants(定数)

定数( constant )は、 const キーワードを使って変数と同じように宣言します。
定数は、文字(character)、文字列(string)、boolean、数値(numeric)のみで使えます。
なお、定数は := を使って宣言できません。

package main

import "fmt"

const Pi = 3.14

func main() {
  const World = "世界"
  fmt.Println("Hello", World)
  fmt.Println("Happy", Pi, "Day")

  const Truth = true
  fmt.Println("Go rules?", Truth)
}

結果

Hello 世界
Happy 3.14 Day
Go rules? true
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