当前位置:网站首页>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)
边栏推荐
- Servlet
- 跨境电商测评自养号团队应该怎么做?
- All questions and answers of database SQL practice niuke.com
- Servlet
- Clojure installation of metabase source code secondary development
- Review Servlet
- The meaning in the status column displayed by PS aux command
- Yoyov5's tricks | [trick8] image sampling strategy -- Sampling by the weight of each category of the dataset
- Record the first data preprocessing process
- Human gene editing technology and ethical issues behind it [personal view, for reference only]
猜你喜欢

Login and registration based on servlet, JSP and MySQL

Build the first power cloud platform

Use com youth. banner. Solution to the inflateexception reported by the banner plug-in

Stock K-line drawing

ThymeleafEngine模板引擎

Error reporting injection of SQL injection

Shandong University machine learning experiment 7 pca+ SVM face recognition
![Chapter 4 of machine learning [series] naive Bayesian model](/img/77/7720afe4e28cd55284bb365a16ba62.jpg)
Chapter 4 of machine learning [series] naive Bayesian model

jenkins-凭证管理

Super details to teach you how to use Jenkins to realize automatic jar package deployment
随机推荐
FPGA interview notes (II) -- synchronous asynchronous D flip-flop, static and dynamic timing analysis, frequency division design, retiming
FPGA面試題目筆記(四)—— 序列檢測器、跨時鐘域中的格雷碼、乒乓操作、降低靜動態損耗、定點化無損誤差、恢複時間和移除時間
LeetCodeT526
Review Servlet
Teach you to write word formula
[IOS development interview] operating system learning notes
箭头函数的this指向
Clear function of ArrayList
View controller and navigation mode
handler
FIFO最小深度计算的题目合集
Sqli-labs less-01
亚马逊、速卖通、Lazada、虾皮平台在用911+VM的环境可以进行产号、养号、补单等操作吗?
Elk log system practice (V): install vector and output data to es and Clickhouse cases
Topic collection of FIFO minimum depth calculation
NLP-D46-nlp比赛D15
Do you know the functions of getbit and setbit in redis?
ThymeleafEngine模板引擎
Which company is better in JIRA organizational structure management?
11. Gesture recognition