"Go foundation" Section 8 formatted output

Output is to print data on a computer screen this section we have to learn about three output mode Go language:. Print (), Println ( ), Printf ().

1.Print()

Print () The main feature is a print data does not wrap .

package main

import "fmt"

func main() {
    a, b := 10, 20
    
    // 输出: Print, 打印数据时不带换行
    fmt.Print(a)
    fmt.Print(b)
}
// 结果:
1020

2. Println()

Println before () has been used before, to wrap output .

package main

import "fmt"

func main() {
    a, b := 10, 20
    // 输出: Println, 打印数据时自带换行
    fmt.Println(a)
    fmt.Println(b)
}
// 结果:
10
20

This time, you know this is the result of 10 20all what does it mean but if you change a programmer point of view, do not know, especially in the case of particularly large amount of code so that it should adopt the following output..:

package main

import "fmt"

func main() {
    a, b := 10, 20
    // 双引号内的内容会原样输出. 注意与变量名之间用逗号分隔
    fmt.Println("a =", a)
    fmt.Println("b =", b)
}
// 结果:
a = 10
b = 20

3. Printf()

In addition to the above two output functions, Go language and a function Printf(): formatted output.

Formatted output line of output transducers may be implemented;

package main

import "fmt"

func main() {
    a, b := 10, 20
    
    // %d 占位符, 表示输出一个整型数据
    // 第一个%d会被变量a的值替换, 第二个%d会被变量b替换
    // \n 表示换行
    fmt.Printf("a = %d\nb = %d", a, b)
}
// 结果:
a = 10
b = 20

Printf () structure is suitable for a plurality of output values ​​of the variables:

package main

import "fmt"

func main() {
    a, b, c := 10, 20, 30
    fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}
// 结果:
a = 10, b = 20, c = 30

About placeholders, will explain in detail in the following sections.

Guess you like

Origin www.cnblogs.com/BlameKidd/p/11620194.html