1
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言語(2. 変数と定数、データ型)

Last updated at Posted at 2025-06-24

はじめに

先日にアップしたはじめてのGo言語(1. 環境構築~Hello world)に続いて、Go言語の基礎を学んだ記録を記事としてまとめてみました。

実行環境

WSL2(Ubuntu 22.04.3 LTS)

変数

  • 変数は「var 変数名 型名」の形で宣言するのが一般的だそうですが...
  • データ型が明確である時は、「var 変数名 = 初期値」の形で宣言することもできるそうです。
    • さらに変数の初期値を設定している場合は、型推論で「変数名 := 初期値」と宣言することもできるそうです。
var.go
package main

import "fmt"

func main() {
    var num int
    num = 123
    fmt.Printf("num=%d\n", num)
}
var.go(型推論版)
package main

import "fmt"

func main() {
    num := 123
    fmt.Printf("num=%d\n", num)
}
実行結果
# go run var.go
num=123

定数

  • 「const 定数名 = 定数値」で定数を宣言できます。
    • 「多くの場合、定数にはデータ型名の指定は不要」とのことですが、逆にどのような場合にデータ型名を指定する必要があるのかが気になります...
const.go
package main

import "fmt"

const num = 345

func main() {
    fmt.Println(num)

    const name = "nkojima"
    fmt.Printf("Hello, %s\n", name)
}
実行結果
# go run const.go
345
Hello, nkojima

データ型

  • データ型はboolstringなど、様々な言語でお馴染みのデータ型もありますが...
  • float32 / float64int8 / int16 / int32 / int64uint8 / uint16 / uint32 / uint64なども使えます。
    • unsignedな整数型が使えるという点では、Javaよりも優れていると感じました。
  • rune(ルーン)というデータ型は、JavaやC#だとchar型に相当するデータ型のようです。
type.go
package main

import "fmt"

func main() {
    var isTest bool = true
    const pi float32 = 3.14159265359
    var id uint = 1234
    var name string = "nkojima"
    var char rune = 'a'

    fmt.Printf("テスト:%t\n", isTest)
    fmt.Printf("円周率:%f\n", pi)
    fmt.Printf("円周率のデータ型:%T\n", pi)
    fmt.Printf("ID:%d\n", id)
    fmt.Printf("IDのデータ型:%T\n", id)
    fmt.Printf("名前:%s\n", name)
    fmt.Printf("1文字:%c\n", char)
}
実行結果
# go run type.go
テスト:true
円周率:3.141593
円周率のデータ型:float32
ID:1234
IDのデータ型:uint
名前:nkojima
1文字:a

参考URL

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