這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
以下摘自The Go Programming Language:
When printing numbers using the fmt package, we can control the radix and format with the %d, %o, and %x verbs, as shown in this example:
o := 0666
fmt.Printf(“%d %[1]o %#[1]o\n”, o) // “438 666 0666”
x := int64(0xdeadbeef)
fmt.Printf(“%d %[1]x %#[1]x %#[1]X\n”, x)
// Output:
// 3735928559 deadbeef 0xdeadbeef 0XDEADBEEF
Note the use of two fmt tricks. Usually a Printf format string containing multiple % verbs would require the same number of extra operands, but the [1] “adverbs” after % tell Printf to use the first operand over and over again. Second, the # adverb for %o or %x or %X tells Printf to emit a 0 or 0x or 0X prefix respectively.
Rune literals are written as a character within single quotes. The simplest example is an ASCII character like ‘a’, but it’s possible to write any Unicode code point either directly or with numeric escapes, as we will see shortly.
Runes are printed with %c, or with %q if quoting is desired: ascii := ‘a’
unicode := ‘ ‘
newline := ‘\n’
fmt.Printf(“%d %[1]c %[1]q\n”, ascii) // “97 a ‘a'”
fmt.Printf(“%d %[1]c %[1]q\n”, unicode) // “22269 ‘ ‘”
fmt.Printf(“%d %[1]q\n”, newline) // “10 ‘\n'”
總結一下,“%[1]”還是格式化第一個參數;“%#”會列印出數值的首碼;而“%q”會加上引號。舉例如下:
package mainimport "fmt"func main() { var c rune = '楠' fmt.Printf("%c %[1]d %#[1]x %[1]q", c)}
執行結果:
楠 26976 0x6960 '楠'