Home > Backend Development > Golang > What are the output methods in go language?

What are the output methods in go language?

青灯夜游
Release: 2023-01-04 20:20:23
Original
3935 people have browsed it

Output method: 1. Print() function, which can be output to the console (no formatting is accepted), syntax "fmt.Print(str)"; 2. Println() function, which can be output to the control Station and line break, the syntax is "fmt.Println(tmp)"; 3. Printf() function can only print out a formatted string; 4. Sprintf() function can format and return a string; 5. Fprintf () function, which can be formatted and output to "io.Writers".

What are the output methods in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

The difference between several output methods in Go language

Print, Println, Printf , <strong>Sprintf</strong> , Fprintf are all public methods in the fmt package. These functions need to be used when printing information. So what is the difference between these functions?

Print:   输出到控制台(不接受任何格式化,它等价于对每一个操作数都应用 %v)
         fmt.Print(str)
Println: 输出到控制台并换行
         fmt.Println(tmp)
Printf : 只可以打印出格式化的字符串。只可以直接输出字符串类型的变量(不可以输出整形变量和整形 等)
         fmt.Printf("%d",a)
Sprintf:格式化并返回一个字符串而不带任何输出。
         s := fmt.Sprintf("a %s", "string") fmt.Printf(s)
Fprintf:格式化并输出到 io.Writers 而不是 os.Stdout。
         fmt.Fprintf(os.Stderr, “an %s\n”, “error”)
Copy after login

Generally choose Printf when you need to format the output information, otherwise use Println

Printf formatted output

1 , General placeholder:

v     值的默认格式。
%+v   添加字段名(如结构体)
%#v  相应值的Go语法表示 
%T    相应值的类型的Go语法表示 
%%    字面上的百分号,并非值的占位符 
Copy after login

2, Boolean value:

%t   true 或 false
Copy after login

3, Integer value:

%b     二进制表示 
%c     相应Unicode码点所表示的字符 
%d     十进制表示 
%o     八进制表示 
%q     单引号围绕的字符字面值,由Go语法安全地转义 
%x     十六进制表示,字母形式为小写 a-f 
%X     十六进制表示,字母形式为大写 A-F 
%U     Unicode格式:U+1234,等同于 "U+%04X"
Copy after login

4. Floating point numbers and complex numbers:

%b     无小数部分的,指数为二的幂的科学计数法,与 strconv.FormatFloat中的 &#39;b&#39; 转换格式一致。例如 -123456p-78 
%e     科学计数法,例如 -1234.456e+78 
%E     科学计数法,例如 -1234.456E+78 
%f     有小数点而无指数,例如 123.456 
%g     根据情况选择 %e 或 %f 以产生更紧凑的(无末尾的0)输出 
%G     根据情况选择 %E 或 %f 以产生更紧凑的(无末尾的0)输出
Copy after login

5. Slice representation of strings and bytes:

%s     字符串或切片的无解译字节 
%q     双引号围绕的字符串,由Go语法安全地转义 
%x     十六进制,小写字母,每字节两个字符 
%X     十六进制,大写字母,每字节两个字符
Copy after login

6. Pointer:

%p     十六进制表示,前缀 0x
Copy after login

There is no 'u' tag here. If integers are of unsigned type, they are printed as unsigned. Similarly, there is no need to specify the size of the operand (int8, int64).

7. For %v, the default format is:

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
Copy after login

It can be seen that the default output format can be specified using %v, unless the output For other formats that are different from the default, you can use %v instead (but it is not recommended)

8. For composite objects:

The elements inside are used as follows Rules for printing:

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

9, width and precision:

The width is the value after %. If not specified, the default value of the value is used, and the precision is Is the value that follows the width. If not specified, the default precision of the value to be printed is used. For example: %9.2f, width 9, precision 2

%f:      default width, default precision 
%9f      width 9, default precision 
%.2f     default width, precision 2 
%9.2f    width 9, precision 2 
%9.f     width 9, precision 0
Copy after login

For numerical values, the width is the minimum width of the area occupied by the numerical value; the precision is the number of digits after the decimal point. But for %g/%G, the precision is the total number of digits. For example, for 123.45, the format %6.2f would print 123.45, while %.4g would print 123.5. The default precision for %e and %f is 6; but for %g , the default precision is the minimum number of digits necessary to determine the value.

For most values, the width is the minimum number of characters to output, with spaces padded if necessary in the formatted form. For strings, the precision is the maximum number of characters output, and will be truncated directly if necessary.

Width refers to the "necessary minimum width". If the width of the result string exceeds the specified width, the specified width will be invalid.

If the width is specified as `*', the width value will be obtained from the parameter.

The number string immediately following "." indicates the precision (if there is only ".", it is ".0"). If an integer indicator (`d', `i', `b', `o', `x', `X', `u') is encountered, the precision indicates the length of the numerical part

If a floating-point indicator (`f') is encountered, it represents the number of digits in the decimal part.

If you encounter a floating-point indicator (`e', `E', `g', `G'), it indicates the number of significant digits

If the precision is set to ` *', the precision value will be extracted from the parameter

For the string %s or the floating point type %f, the precision can truncate the length of the data. As follows.

func main() {
    a := 123
    fmt.Printf("%1.2d\n", a)    //123,宽度为1小于数值本身宽度,失效,而精度为2,无法截断整数
    b := 1.23
    fmt.Printf("%1.1f\n", b)    //1.2,精度为1,截断浮点型数据
    c := "asdf"
    fmt.Printf("%*.*s\n", 1, 2, c) //as,利用&#39;*&#39;支持宽度和精度的输入,并且字符串也可以利用精度截断
}
Copy after login

10. Other flags:

+     总打印数值的正负号;对于%q(%+q)保证只输出ASCII编码的字符。 
-     左对齐 
#     备用格式:为八进制添加前导 0(%#o),为十六进制添加前导 0x(%#x)或0X(%#X),为 %p(%#p)去掉前导 0x;对于 %q,若 strconv.CanBackquote 返回 true,就会打印原始(即反引号围绕的)字符串;如果是可打印字符,%U(%#U)会写出该字符的Unicode编码形式(如字符 x 会被打印成 U+0078 &#39;x&#39;)。 
&#39; &#39;  (空格)为数值中省略的正负号留出空白(% d);以十六进制(% x, % X)打印字符串或切片时,在字节之间用空格隔开 
0     填充前导的0而非空格;对于数字,这会将填充移到正负号之后
Copy after login

For every function of the Printf class, there is a Print function. This function does not accept any formatting. It is equivalent to each operand. Both apply %v. Another variable parameter function, Println, will insert blanks between the operands and append a newline character

at the end. If the placeholder is not considered, if the operand is an interface value, its internal specific value will be used. , rather than the interface itself. As shown below:

package main
 
import (
	"fmt"
)
 
type Sample struct {
	a   int
	str string
}
 
func main() {
	var i interface{} = Sample{1, "a"}
	fmt.Printf("%v\n", i)      //{1 a}
}
Copy after login

11. Display parameter placeholders:

Go supports displaying parameter placeholders by specifying the order of their output in the output format, as shown below :

func main() {
    fmt.Printf("%[2]d, %[1]d\n", 11, 22)  //22, 11,先输出第二个值,再输出第一个值
}
Copy after login

12. Formatting error:

If invalid arguments are provided to the placeholder (such as providing a string to %d), a formatting error will occur. All errors begin with "%!", sometimes followed by a single character (placeholder), and end with a description enclosed in parentheses.

func main() {
	var i int = 1
	fmt.Printf("%s\n", i)  //%!s(int=1)
}
Copy after login

Output example

package main
import "fmt"
import "os"
type point struct {
    x, y int
}
func main() {
    //Go 为常规 Go 值的格式化设计提供了多种打印方式。例如,这里打印了 point 结构体的一个实例。
    p := point{1, 2}
    fmt.Printf("%v\n", p) // {1 2}
    //如果值是一个结构体,%+v 的格式化输出内容将包括结构体的字段名。
    fmt.Printf("%+v\n", p) // {x:1 y:2}
    //%#v 形式则输出这个值的 Go 语法表示。例如,值的运行源代码片段。
    fmt.Printf("%#v\n", p) // main.point{x:1, y:2}
    //需要打印值的类型,使用 %T。
    fmt.Printf("%T\n", p) // main.point
    //格式化布尔值是简单的。
    fmt.Printf("%t\n", true)
    //格式化整形数有多种方式,使用 %d进行标准的十进制格式化。
    fmt.Printf("%d\n", 123)
    //这个输出二进制表示形式。
    fmt.Printf("%b\n", 14)
    //这个输出给定整数的对应字符。
    fmt.Printf("%c\n", 33)
    //%x 提供十六进制编码。
    fmt.Printf("%x\n", 456)
    //对于浮点型同样有很多的格式化选项。使用 %f 进行最基本的十进制格式化。
    fmt.Printf("%f\n", 78.9)
    //%e 和 %E 将浮点型格式化为(稍微有一点不同的)科学技科学记数法表示形式。
    fmt.Printf("%e\n", 123400000.0)
    fmt.Printf("%E\n", 123400000.0)
    //使用 %s 进行基本的字符串输出。
    fmt.Printf("%s\n", "\"string\"")
    //像 Go 源代码中那样带有双引号的输出,使用 %q。
    fmt.Printf("%q\n", "\"string\"")
    //和上面的整形数一样,%x 输出使用 base-16 编码的字符串,每个字节使用 2 个字符表示。
    fmt.Printf("%x\n", "hex this")
    //要输出一个指针的值,使用 %p。
    fmt.Printf("%p\n", &p)
    //当输出数字的时候,你将经常想要控制输出结果的宽度和精度,可以使用在 % 后面使用数字来控制输出宽度。默认结果使用右对齐并且通过空格来填充空白部分。
    fmt.Printf("|%6d|%6d|\n", 12, 345)
    //你也可以指定浮点型的输出宽度,同时也可以通过 宽度.精度 的语法来指定输出的精度。
    fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
    //要最对齐,使用 - 标志。
    fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
    //你也许也想控制字符串输出时的宽度,特别是要确保他们在类表格输出时的对齐。这是基本的右对齐宽度表示。
    fmt.Printf("|%6s|%6s|\n", "foo", "b")
    //要左对齐,和数字一样,使用 - 标志。
    fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
    //到目前为止,我们已经看过 Printf了,它通过 os.Stdout输出格式化的字符串。Sprintf 则格式化并返回一个字符串而不带任何输出。
    s := fmt.Sprintf("a %s", "string")
    fmt.Println(s)
    //你可以使用 Fprintf 来格式化并输出到 io.Writers而不是 os.Stdout。
    fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
Copy after login

[Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What are the output methods in go language?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template