いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-09 (Basic Types, 基本型, Tour of Go)

概要

Tour of Go の - Basic types についてのサンプル。

tour.golang.org

今回は大して書くことがあまり無いのですが、どの言語にも基本型があるようにGoにも基本型があります。 以下のものです。

  • bool
  • string
  • int (int8, int16, int32, int64)
  • uint (uint8 , uint16, uint32, uint64, uintptr)
  • byte (uint8 の 別名)
  • rune (int32 の 別名)
  • float (float32, float64)
  • complex (complex32, complex64)

ほぼ、どの言語にも同じような名前でありますね。

rune だけGoでしか見たことがない名前でした。

この型は文字を表します。int32の別名となっていて、Unicodeの code point を表します。

よく間違えそうなのが、以下の点。

  • rune は文字なので、runeのスライスをlenすると文字数が返る
  • byte はバイトなので、byteのスライスをlenするとバイト数が返る

文字列を rune のスライスにするには

   // 文字列を rune の スライスに変換
    string2 := "あいう"
    rune2 := []rune(string2)
    fmt.Println(rune2)

ってします。

また、文字列をバイトのスライスにするには

   // 文字列を byte の スライスに変換
    bytes1 := []byte(string2)
    fmt.Println(bytes1)

ってします。

んで、

   // rune は文字数、byte はバイト数
    fmt.Printf("len(rune2): %d, len(bytes1): %d\n", len(rune2), len(bytes1))

ってすると、結果は

[12354 12356 12358]
[227 129 130 227 129 132 227 129 134]
len(rune2): 3, len(bytes1): 9

ってなります。

サンプル

package tutorial

import "fmt"

// BasicTypes は、 Tour of Go - Basic types (https://tour.golang.org/basics/11) の サンプルです。
func BasicTypes() error {
    // ------------------------------------------------------------
    // Go言語の基本型は以下
    //
    // - bool
    // - string
    // - int     (int8,   int16,  int32,  int64)
    // - uint    (uint8 , uint16, uint32, uint64, uintptr)
    // - byte    (uint8 の 別名)
    // - rune    (int32 の 別名)
    // - float   (float32, float64)
    // - complex (complex32, complex64)
    // ------------------------------------------------------------
    //noinspection GoVarAndConstTypeMayBeOmitted
    var (
        boolVal bool   = true
        maxInt  int64  = 1<<63 - 1
        maxUInt uint64 = 1<<64 - 1
        byteVal byte   = 42
        runeVal rune   = 'a'
    )

    //noinspection GoBoolExpressions
    fmt.Println(boolVal, maxInt, maxUInt, byteVal, runeVal)

    return nil
}

try-golang/tutorial_gotour_05_basictypes.go at master · devlights/try-golang · GitHub


過去の記事については、以下のページからご参照下さい。

  • いろいろ備忘録日記まとめ

devlights.github.io

サンプルコードは、以下の場所で公開しています。

  • いろいろ備忘録日記サンプルソース置き場

github.com

github.com

github.com