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?

Go言語の変数定義

Posted at

はじめに

Go言語の変数定義の仕方にはいくつか方法があります。
Goを学び始めると、変数定義の方法の柔軟性にとても驚きます。

単独変数の定義

初期値なし変数

  • 定義:変数宣言(var)変数名 変数型
  • 例:
var s string

初期値あり変数

  • 定義:var 変数名 変数型 = 値
  • 例:
var s string = "Golang is fun and simple"
var i int = 10

初期値ありの場合、値から変数を予測できるため(型推論:type inference)、変数宣言と変数名を省略可能です。

  • 定義:変数名 := 値
  • 例:
line := "Golang is fun and simple" // stringだと推論してくれる
num := 10 // intだと推論してくれる

複数変数の定義

初期値なしの場合

  • 定義:var 変数名1, 変数名2,...変数名n 変数型
  • 例:
var num1, num2, num3 int

初期値ありの場合

  • 定義:var 変数名1, 変数名2,...変数名n 変数型 = 値1, 値2,...値n
  • 例:
var num1, num2 num3 int = 2, 3, 5
  • エラー例:
var num1, num2, num3 int = 10

複数変数でも、型推論のおかげでvarと変数型を省略できます。その場合も、型推論用の:=を用います。

  • 例:
num1, num2, num3 := 2, 3, 5

複数型の変数をまとめて定義

  • 定義:
    var (
      変数名1 変数型 = 値
      変数名2 変数型
      変数名3 := 値
      変数名4, 変数名5 変数型 = 値
      変数名6, 変数名7 変数型
      変数名8, 変数名9 := 値
    )

  • 例:

var (
      num1         int     = 2
      line1        string
      line2               := "Golang"
      num2, num3   int     = 3, 5
      line3, line4 string
      num4, num5          := 7, 11
    )

初期値なし変数のデフォルト値

未初期化の変数は、型に応じたゼロ値で初期化される。

デフォルト値:

  • 文字列は空文字列 ""
  • 整数は 0
  • ブール値は 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?