簡單介紹標準庫fmt的基本使用

iamcyan發表於2020-12-14

常見verbs

General

%v     變數的預設格式
%#v    使用go語法來表示這個值
%T     變數型別
func main() {
    s := []string{"a", "b", "c"}
    fmt.Printf("%v\n", s)       //["a", "b", "c"]
    fmt.Printf("%#v\n", s)  //[]string{"a", "b", "c"}
    fmt.Printf("%T\n", s)       //[]string
}

Boolean

%t    變數的布林值
t := true
fmt.Printf("%t\n", t)   //true

Integer

%b    base 2
%c    the character represented by the corresponding Unicode code point
%d    base 10
%o    base 8
%O    base 8 with 0o prefix
%q    a single-quoted character literal safely escaped with Go syntax.
%x    base 16, with lower-case letters for a-f
%X    base 16, with upper-case letters for A-F
  1 package main
  2
  3 import (
  4     "fmt"
  5 )
  6
  7 func main() {
  8     n := 10
  9     fmt.Printf("%b\n", n)       //1010
 10     fmt.Printf("%c\n", 97)      //a
 11     fmt.Printf("%d\n", 100)     //100
 12     fmt.Printf("%o\n", 8)       //10
 13     fmt.Printf("%O\n", 8)       //0o10
 14     fmt.Printf("%q\n", 97)      //'a'
 15     fmt.Printf("%x\n", 15)      //f
 16     fmt.Printf("%X\n", 15)      //F
 17 }

Slice

%p    address of 0th element in base 16 notation, with leading 0x
  1 package main
  2
  3 import (
  4     "fmt"
  5 )
  6
  7 func main() {
  8     s := []string{"cheng", "xiao", "shuo"}
  9     fmt.Printf("%p\n", s)   //0xc000054180
 10 }

預設格式%v

bool:                    %t
int, int8 etc.:          %d
uint, uint8 etc.:        %d, %#x if printed with %#v
float32, complex64, etc: %g
string:                  %s
chan:                    %p
pointer:                 %p

複合型別列印的預設格式

struct:             {field0 field1 ...}
array, slice:       [elem0 elem1 ...]
maps:               map[key1:value1 key2:value2 ...]
pointer to above:   &{}, &[], &map[]

Pointer

%p    base 16 notation, with leading 0x
The %b, %d, %o, %x and %X verbs also work with pointers,
formatting the value exactly as if it were an integer.
  1 package main
  2
  3 import (
  4     "fmt"
  5 )
  6
  7 func main() {
  8     s := []int64{1,2,3}
  9     fmt.Printf("%p\n", s)
 10     fmt.Printf("%p\n", &s)
 11     fmt.Printf("%b\n", s)
 12     fmt.Printf("%b\n", &s)
 13     fmt.Printf("%d\n", s)
 14     fmt.Printf("%d\n", &s)
 15     fmt.Printf("%o\n", s)
 16     fmt.Printf("%o\n", &s)
 17 }

輸出:

0xc0000b6020
0xc0000a6020
[1 10 11]
&[1 10 11]
[1 2 3]
&[1 2 3]
[1 2 3]
&[1 2 3]

###golang fmt pkg 中的例子:

package main

import (
    "fmt"
    "math"
    "time"
)

func main() {
    integer := 23
    // Each of these prints "23" (without the quotes).
    fmt.Println(integer)
    fmt.Printf("%v\n", integer)
    fmt.Printf("%d\n", integer)

    // The special verb %T shows the type of an item rather than its value.
    fmt.Printf("%T %T\n", integer, &integer)
    // Result: int *int

    // Booleans print as "true" or "false" with %v or %t.
    truth := true
    fmt.Printf("%v %t\n", truth, truth)
    // Result: true true

    answer := 42
    fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
    // Result: 42 42 2a 52 101010

    pi := math.Pi
    fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
    // Result: 3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00

    point := 110.7 + 22.5i
    fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
    // Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)

    smile := '?'
    fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
    // Result: 128512 128512 ? '?' U+1F600 U+1F600 '?'

    placeholders := `foo "bar"`
    fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
    // Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`

    isLegume := map[string]bool{
        "peanut":    true,
        "dachshund": false,
    }
    fmt.Printf("%v %#v\n", isLegume, isLegume)
    // Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}

    person := struct {
        Name string
        Age  int
    }{"Kim", 22}
    fmt.Printf("%v %+v %#v\n", person, person, person)
    // Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}

    pointer := &person
    fmt.Printf("%v %p\n", pointer, (*int)(nil))
    // Result: &{Kim 22} 0x0
    // fmt.Printf("%v %p\n", pointer, pointer)
    // Result: &{Kim 22} 0x010203 // See comment above.

    greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
    fmt.Printf("%v %q\n", greats, greats)
    // Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]

    kGreats := greats[:3]
    fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
    // Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}

    cmd := []byte("a⌘")
    fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
    // Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98

    now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.
    fmt.Printf("%v %q\n", now, now)
    // Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
}

例子

Errorf()

package main

import (
    "fmt"
)

func main() {
    const name, id = "bueller", 17
    err := fmt.Errorf("user %q (id %d) not found", name, id)
    fmt.Println(err.Error())

}

Fprint()、Fprintf()、Fprintln()。輸出內容到io.writer

package main

import (
    "fmt"
    "os"
)

func main() {
    const name, age = "Kim", 22
    n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
    }
    fmt.Print(n, " bytes written.\n")

    n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
    }
    fmt.Printf("%d bytes written.\n", n)

    n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
    }
    fmt.Println(n, "bytes written.")
}

Fscan()、Fscanf()、Fscanln()

package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    var (
        i int
        b bool
        s string
    )
    r := strings.NewReader("5 true gophers")
    n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
    }
    fmt.Println(i, b, s)
    fmt.Println(n)

s := `dmr 1771 1.61803398875
    ken 271828 3.14159`
    r := strings.NewReader(s)
    var a string
    var b int
    var c float64
    for {
        n, err := fmt.Fscanln(r, &a, &b, &c)
        if err == io.EOF {
            break
        }
        if err != nil {
            panic(err)
        }
        fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章