LoginSignup
9
6

More than 3 years have passed since last update.

Golangのフォーマット指定子についてカンペを作っておいた。package fmt

Posted at

たびたびGolangのフォーマット指定子まわりについて困惑してfmtのdocを見たり検索したりしているので、知識を整理する目的でGistにまとめておきます。(+vとか#vとか。)

fmt.go
package main

import (
    "fmt"
    "strings"
)

type user struct {
    id   int
    name string
}

func main() {
    u := user{1001, "taro"}
    fmt.Printf("valInt[%%v]  :  %v\n", u) // デフォルトのフォーマット
    fmt.Printf("valInt[%%+v] : %+v\n", u) // 値が構造体のときフィールド名もつく
    fmt.Printf("valInt[%%#v] : %#v\n", u) // Goの構文表現(=Goのソースコード形式)
    fmt.Printf("Type[%%T]    : %T\n", u)  // 値の型(Type)

    intervalString(20)

    a := 1234
    fmt.Printf("valInt[%%d]  : %d\n", a)      // %d 10進数表記
    fmt.Printf("valInt[%%b]  : %b\n", a)      // %b 2進数表記
    fmt.Printf("valInt[%%o]  : %o\n", a)      // %o 8進数表記
    fmt.Printf("valInt[%%x]  : %x\n", a)      // %x 16進数表記
    fmt.Printf("Boolean[%%t] : %t\n", a == a) // 真偽値(true or false)

    intervalString(20)

    b := 12.0 / 34.0
    fmt.Printf("valFloat[%%f]   : %f\n", b)
    fmt.Printf("valFloat[%%.2f] : %.2f\n", b)

    intervalString(20)

    str := "寿司🍣"
    fmt.Printf("valStr[%%s]  : %s\n", str)  // %s 文字列表記
    fmt.Printf("valStr[%%q]  : %q\n", str)  // %q 文字列表記(ダブルクオーテーション付き)
    fmt.Printf("valStr[%%X]  : % X\n", str) // %X 16進数表記(文字列につき1文字2バイト)

    fmt.Printf("Pointer[%%p] : %p\n", &str) // ポインタ

    s := fmt.Sprintf("str = %s", str) // Sprintfは返り値にフォーマットした
    fmt.Println(s)                    // 文字列を返す

    intervalString(20)

    U := '\101'
    fmt.Printf("Unicodeコードポイント[\\101]  : %c\n", U)
    fmt.Printf("ユニコードフォーマット[\\101] : %U\n", U)

    intervalString(20)

    var i interface{} = "print content of interface"
    fmt.Printf("Interface[%%v] : %v\n", i)

}

func intervalString(cnt int) {
    fmt.Println(strings.Repeat("-", cnt))
}

/*
valInt[%v]  :  {1001 taro}
valInt[%+v] : {id:1001 name:taro}
valInt[%#v] : main.user{id:1001, name:"taro"}
Type[%T]    : main.user
--------------------
valInt[%d]  : 1234
valInt[%b]  : 10011010010
valInt[%o]  : 2322
valInt[%x]  : 4d2
Boolean[%t] : true
--------------------
valFloat[%f]   : 0.352941
valFloat[%.2f] : 0.35
--------------------
valStr[%s]  : 寿司🍣
valStr[%q]  : "寿司🍣"
valStr[%X]  : E5 AF BF E5 8F B8 F0 9F 8D A3
Pointer[%p] : 0x40c148
str = 寿司🍣
--------------------
Unicodeコードポイント[\101]  : A
ユニコードフォーマット[\101] : U+0041
--------------------
Interface[%v] : print content of interface
*/

参考

fmt - GoDoc

Go言語 - %Tや%vの書式で出力される文字列 - 覚えたら書く

忘れがちなGo言語の書式指定子を例付きでまとめた - Qiita

Go by Example: String Formatting


この記事は著者のブログからの転載記事となります。

Golangのフォーマット指定子についてカンペを作っておいた。package fmt - DOT NOTES

9
6
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
9
6