Tips for using fmt.printf in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The following excerpt from 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 I N 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 both FMT tricks. Usually a Printf format string containing multiple% verbs would require the same number of extra operands, but the [1] "a Dverbs "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 is 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'll see shortly.

Runes is printed with%c, or with%q if quoting is desired:ascii: = ' a '
Unicode: = ' '
NewLine: = ' \ n '
Fmt. Printf ("%d%[1]c%[1]q\n", ASCII)//"$ A ' a '"
Fmt. Printf ("%d%[1]c%[1]q\n", Unicode)//"22269" "
Fmt. Printf ("%d%[1]q\n", newline)//"Ten ' \ n '"

Sum up, " %[1] " or format the first argument; "" %# prints the prefix of the numeric value, and " %q " adds quotation marks. Examples are as follows:

package mainimport "fmt"func main() {    var c rune = '楠'    fmt.Printf("%c %[1]d %#[1]x %[1]q", c)}

Execution Result:

楠 26976 0x6960 '楠'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.