当前位置:网站首页>FMT package usage of go and string formatting
FMT package usage of go and string formatting
2022-06-11 06:14:00 【CK continues to grow】
Catalog
1. Standard library fmt Several outputs are available / Input correlation function .
3. Use fmt Problems encountered in formatting
fmt The package provides something similar to C Of print and scan Function to implement formatting I/O. fmt It mainly provides output and input functions and string formatting methods .
1. Standard library fmt Several outputs are available / Input correlation function .
1. Print A series of functions will output the content to the standard output of the system
func Print(a ...interface{}) (n int, err error)2.Printf The function supports formatting the output string to the standard output of the system
func Printf(format string, a ...interface{}) (n int, err error)
3. Println Function adds a newline at the end of the output , Output to the standard output of the system
func Println(a ...interface{}) (n int, err error)4. Fprint A series of functions will output the content to a io.Writer Variables of interface type w in , We usually use this function to write to a file .
func Fprint(w io.Writer, a ...interface{}) (n int, err error)
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)5. Sprint A series of functions will generate the incoming data and return a string .
func Sprint(a ...interface{}) string
func Sprintf(format string, a ...interface{}) string
func Sprintln(a ...interface{}) string6. Errorf Functions are based on format Parameter generates a formatted string and returns an error containing the string .
func Errorf(format string, a ...interface{}) errorbe relative to fmt Output ,fmt Corresponding input functions are provided :
1. Get user input from standard input .
func Scan(a ...interface{}) (n int, err error)2. according to format The format specified by the parameter , Read data from standard input
func Scanf(format string, a ...interface{}) (n int, err error)
3. Getting data from standard input , Until the newline character is obtained
func Scanln(a ...interface{}) (n int, err error)4. and Fpritn Corresponding Fscan, from io.Reader Read data from
func Fscan(r io.Reader, a ...interface{}) (n int, err error)
func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)5. and Sprint Corresponding Sscan, Read from a string
func Sscan(str string, a ...interface{}) (n int, err error)
func Sscanln(str string, a ...interface{}) (n int, err error)
func Sscanf(str string, format string, a ...interface{}) (n int, err error)The standard provides input from the standard 、 Files are read in many forms , And output to standard input 、 Documents, etc. . Some of these functions also provide the ability to output formatted data as placeholders .
2. Format data placeholder
*printf A series of functions support format Format parameters , The actual value of the variable that the placeholder will be replaced , Here we divide the data by format data type
Here we first define a Person Structure , As a follow-up example :
type Person struct {
Name string
Age int
}
person := &Person{
Name: "Xiao Ming",
Age: 18,
}1. Universal
| Place holder | explain | example |
|---|---|---|
| %v | go Default print format for | Print person structure :&{Xiao Ming 18} |
| %+v | When printing structures , Add field name | Print person structure :&{Name:Xiao Ming Age:18} |
| %#v | It's worth it go Grammar said | Print person structure : &main.Person{Name:"Xiao Ming", Age:18} |
| %T | go The type of median | String slice formatting :[]string |
| %% | Print the original % Symbol |
2. bool type
| Place holder | explain | example |
|---|---|---|
| %t | format bool Type variable | true/false |
3. integer
| Place holder | explain | example |
|---|---|---|
| %b | int The format is binary data | for example 65 The corresponding value is :1000001 |
| %c | int The type corresponds to Unicode The character represented by the code point | for example 65 Corresponding to letters A |
| %d | Format as decimal integer | |
| %o | Format as octal integer | for example 65 Format output :101 |
| %O | Format as band 0o Prefix octal integer | for example 65 Format output :0o101 |
| %q | The value is enclosed in single quotes go Syntax character literal , Secure escape representations are used when necessary | |
| %x | Expressed in hexadecimal , Use a-f | for example 255 Output is ff |
| %X | Expressed in hexadecimal , Use A-F | for example 255 Output is FF |
| %U | Expressed as Unicode Format :U+1234, Equivalent to "U+%04X" |
4. Floating point and complex number
| Place holder | explain | example |
|---|---|---|
| %b | format bool type | |
| %e | Scientific enumeration ,e Express | 123.321 The formatted output of : 1.233210e+02 |
| %E | Scientific enumeration ,E Express | 123.321 The formatted output of : 1.233210E+02 |
| %f | There is a decimal format , No exponential representation | 123.321 The formatted output of :123.321 |
| %F | Same as %f | |
| %g | According to the actual situation %e or %f Output , If the number is large %e Output | |
| %G | According to the actual situation %E or %f Output , If the number is large %E Output | |
| %x | Each byte is represented by two hexadecimal bytes ,a-f Express | 123.321 Format output :0x1.ed48b43958106p+06 |
| %X | Each byte is represented by two hexadecimal bytes ,A-F Express | 123.321 Format output :0X1.ED48B43958106P+06 |
5. Slicing of strings and bytes
| Place holder | explain | example |
|---|---|---|
| %s | Direct output string or []byte | “A1b Add 2c3” Format output :A1b Add 2c3 |
| %q | A string in double quotation marks | “A1b Add 2c3” Format output :"A1b Add 2c3" |
| %x | Each byte is represented by two hexadecimal bytes ,a-f Express | “A1b Add 2c3” Format output :413162e58aa0326333 |
| %X | Each byte is represented by two hexadecimal bytes ,A-F Express | “A1b Add 2c3” Format output :413162E58AA0326333 |
6. The pointer
| Place holder | explain | example |
|---|---|---|
| %p | 0x The first hexadecimal number indicates | person Format output :0xc0000a7248 |
7. Width identifier
The width is followed by a % The following decimal number specifies , If the width is not specified , The value is not filled unless it is required . Precision is specified by the decimal number following the dot , No indication precision is specified 0. Examples are as follows
| Place holder | explain | example |
|---|---|---|
| %f | Default width , Default precision | |
| %9f | Width 9, Default precision | 123.321 Format output :123.321000 |
| %.2f | Default width , precision 2 | 123.321 Format output :123.32 |
| %9.2f | Width 9, precision 2 | 123.321 Format output : 123.32, Front complement 4 Empty |
| %9.f | Width 9, precision 0 | 123.321 Format output : 123, Front complement 6 Empty |
8. Other placeholders
3. Use fmt Problems encountered in formatting
1. String() Method to format infinite recursion
type X string
func (x X) String() string {
return fmt.Sprintf("<%s>", x)
}
func main (){
var x X
x = "hello"
fmt.Print(x.String())
}When calling x.String() When the method is used ,X Of String() Method call fmt.Sprintf when , That's when it calls x Of String() Method to format a string, resulting in an infinite loop recursion . Here we need to talk about String() The method is modified as follows :
func (x X) String() string {
return fmt.Sprintf("<%s>", string(x))
}2. If an invalid argument is supplied to the placeholder , The generated string will contain a description of the problem , Not the result you want . for example :
foo := "bar"
fmt.Printf("%d", foo)
// Print out :%!d(string=bar)
边栏推荐
- [daily exercise] 217 Duplicate element exists
- Matlab实现均值滤波与FPGA进行对比,并采用modelsim波形仿真
- Teach you to write word formula
- ERROR 1215 (HY000): Cannot add foreign key constraint
- FPGA面试题目笔记(一)——FPGA开发流程、亚稳态和竞争冒险、建立保持时间、异步FIFO深度等
- go的fmt包使用和字符串的格式化
- SQLI_ LIBS range construction and 1-10get injection practice
- Chapter 6 of machine learning [series] random forest model
- FPGA面试题目笔记(二)——同步异步D触发器、静动态时序分析、分频设计、Retiming
- FPGA面试题目笔记(四)—— 序列检测器、跨时钟域中的格雷码、乒乓操作、降低静动态损耗、定点化无损误差、恢复时间和移除时间
猜你喜欢

山东大学项目实训之examineListActivity

Build the first power cloud platform

箭头函数的this指向

Goodbye 2021 Hello 2022

Yonghong Bi product experience (I) data source module

All the benefits of ci/cd, but greener

Shandong University machine learning experiment 7 pca+ SVM face recognition

Simple knapsack problem

Servlet

What happened to the young man who loved to write code -- approaching the "Yao Guang young man" of Huawei cloud
随机推荐
我们真的需要会议耳机吗?
Servlet
学好C语言从关键字开始
Méthode de la partie du tableau
山东大学项目实训之examineListActivity
Sqoop installation tutorial
Sqli-labs less-01
Functional interface lambda, elegant code development
Shandong University machine learning experiment VI k-means
Solution to slow connection speed of ojdbc under Linux system
Shandong University machine learning experiment 7 pca+ SVM face recognition
Matlab实现均值滤波与FPGA进行对比,并采用modelsim波形仿真
Linux Installation redis
[must see for game development] 3-step configuration p4ignore + wonderful Q & A analysis (reprinted from user articles)
Instanceof and type conversion
ThymeleafEngine模板引擎
Using idea to add, delete, modify and query database
Implementation of data access platform scheme (Youzu network)
Warmly celebrate that yeyanxiu, senior consultant of Longzhi, won the title of "atlassian Certified Expert"
autojs,读取一行删除一行,停止自己外的脚本