Summary of print output methods in Go language

Table of contents

1. Print function

2. Print function

3. Println function

4. Sprintln() function

5. Fprintln() function

6. Fprintf() function

7. Sprintf() function

8. Errorf() function

9. println() function

10. print() function

The difference between println(), fmt.Println(), print() and fmt.Print()

Summarize


picture

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

Since many fans left messages in the background to inquire about Go development technical information, I quickly took some time on weekends and late at night to plan the content of articles about the Go series. I think it can be divided into three stages. The first stage is The entire syntax of Go. The second stage is the advanced content of Go involving distributed high concurrency. The third stage is back-end development, web framework and database operation part.

In previous articles, we also gave a general introduction to Go, including some open source projects and learning materials. For details, please refer to the recommended reading at the end of the article.

Original text: Summary of printout methods in Go language 


 

There are nearly 60 articles in the first stage, and the general contents are as follows:

【Go first stage】

  1. "Advanced features, development trends, and recommended most popular open source projects of Go language"

  2. "Go 1.21 stable version and new features detailed explanation"

  3. "Detailed Explanation of Go's Multi-Terminal Development Environment and Compiler Construction (Pictures and Text)"

  4. "Go Coding, Standards First"

  5. "Detailed introduction to the development of Go code packages and custom packages"

  6. "Go Command Operation Summary Tutorial"

  7. " Summary of printout methods in Go language  "

  8. "Exploring Go Language Variables: Flexible Storage of Data"

  9. "Decryption of Go Language Constants: Constant Values"

  10. "In-depth understanding of data types in Go language"

  11. "The Secret of String Operations in Go Language: Efficiently Processing Text"

  12. "Comprehensive analysis and pit digging of Go's process control (if, for, switch, goto)"

  13. "String Traversal Techniques in Go: Easily Manipulate Text"

  14. "Go language gconv type conversion: seamless conversion of data"

  15. "Using strconv to convert Go's int, float, and string types to each other: Flexible conversion of data types"

  16. "Go's Operator Decryption: Exploring the Secrets of Computation"

  17. "Expression Analysis in Go: Understanding the Core of Code"

  18. "Go's slice technique: Flexible operation of ordered collections"

  19. "In-depth understanding and in-depth analysis of Go language slices (Slice): Exploring the underlying mechanism"

  20. "Go's Slice Tips: Improving Code Efficiency"

  21. "Go's Range Traversal Revealed: Master Iteration Skills and Efficiently Process Data Collections"

  22. "Go's rune analysis: in-depth understanding of character processing"

  23. "The Secret of Map (Collection) Operation in Go Language: Mastering Efficient Mapping Skills"

  24. " Go Language Keyword Analysis: Understanding Key Code Elements "

  25. "Go Language Mapping Skills: Flexible Operation of Data Collections"

  26. "Go language assignment and (deep) copy analysis: in-depth analysis of data processing"

  27. "Parsing Arrays in Go Language: Efficiently Processing Ordered Data"

  28. "Go's initial use of arrays and how to use them as function parameters"

  29. "Comparison of the Differences and Features of Go's Built-in Data Structures Array, Slice, and Map"

  30. "The Art of Error Handling in Go: An In-depth Study of the Error Handling Mechanism of Go Language"

  31. "A Brief Discussion on Golang's Controversial Error: Discussing Its Advantages, Disadvantages and Application Scenarios"

  32. "The Wonderful World of Go Pointers: Analyzing Pointer Usage in Go Language"

  33. "The Charm of Go Methods: Mastering the Skills of Using Methods in Go Language"

  34. "Exploring Go Modular Programming: The Design and Use of Modules in Go Language"

  35. "The Wonderful Journey of Go Functions: In-depth Understanding of Functional Characteristics in Go Language"

  36. "The Difference Between Go Functions and Methods: Revealing Their Commonalities and Differences"

  37. "The Charm of Go Recursive Functions: Exploring the Magical Use of Recursion in Go Language"

  38. "The secret of Go's efficient built-in functions: Go language built-in functions commonly used in development"

  39. "Exploration of Go Functional Programming: Advantages, Disadvantages and Practical Explanation of Module Application"

  40. "The Charm of Go's Higher-Order Functions: Mastering Functional Programming in Go Language"

  41. "Detailed introduction to the role and use of Go's higher-order functions"

  42. "The Wonderful World of Go Interfaces: In-depth Understanding of Interface Features in Go Language"

  43. "Black Box Analysis of Go Garbage Collection: Exploring the Garbage Collection Mechanism in Go Language"

  44. "Go Quickly Integrate Log Module: Log Module Integration Guide in Go Language Framework"

  45. "Go Structure (struct) Analysis: Master the use skills of structures in Go language"

  46. "Go Performance Testing Techniques Revealed: Optimizing the Performance of Go Language Programs"

  47. "Go Debugging & Unit Testing: Debugging and Testing Skills in Go Language Development"

  48. "Comprehensive Analysis of Go Time Operations: Master the Skills of Time Processing"

  49. "The underlying implementation of Go function closures: an in-depth discussion of the principles of closures in the Go language"

  50. "The Secret of Go Concurrency Safety: In-depth understanding of the implementation principle of sync.Map, the concurrency safety in Go language"

  51. "The Wonderful World of Context: Basics of Go Concurrent Programming: What is context and exploring the application and practice of context in Go language"

  52. "Go package manager tool mod"

  53. "Comparison of package management tools in Go language: Go Modules and dep"

  54. "Go dependency management tool dep"

  55. "Analysis of Go Memory Management and Garbage Collection Mechanism"

  56. "How to use the logging package in Go"

  57. "Communication between Go Executors"

  58. "Go Coroutines: Parallel Computing"

Printout in Go language is a very common tool for developers when debugging and viewing program running results. In Go language, you can use the function provided by the fmt package to print output.

In this article, we will summarize the following printout methods of Go: println(), print(), fmt.Print(), fmt.Printf(), fmt.Println(), fmt.Sprintln(), fmt.Fprintln() , the differences, functions and usage of fmt.Fprintf(), fmt.Sprintf() and Errorf().

picture

First, we need to import the fmt package at the beginning of the Go file:

import "fmt"

Next, we can use the Print, Printf and Println functions in the fmt package to print output.

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

1. Print function

The Print function is used to print the given parameters to the standard output without line breaks.

Multiple parameters can be passed in, separated by spaces.

The sample code is as follows:

fmt.Print("Hello", "-", "SteveRocket") // Hello-SteveRocket

2. Print function

The Printf function is used to print the given parameters to the standard output in the specified format without line breaks.

Multiple parameters can be passed in. The first parameter is the format string, and the following parameters are the values ​​to be printed.

Placeholders can be used in the format string to indicate the type and format of the value to be printed.

The sample code is as follows:

name := "SteveRocket"

age := 28

// Similar to C language

fmt.Printf("My name is %s and i am %d year old.", name, age) //My name is SteveRocket and i am 28 year old.

3. Println function

The Println function is used to print the given parameters to the standard output, adding a newline character at the end.

Multiple parameters can be passed in, separated by spaces.

The sample code is as follows:

fmt.Println("\n33 + 44 =", 33+44) // 33 + 44 = 77

4. Sprintln() function

The Sprintln() function is used to convert the given parameters into strings and return a new string containing these strings.

Multiple parameters can be passed in, separated by spaces.

The sample code is as follows:

infos := fmt.Sprintln("Hello", name, age)

fmt.Println(infos) // Hello SteveRocket 28

5. Fprintln() function

The Fprintln() function is used to print the given parameters to the specified io.Writer interface and add a newline character at the end.

Multiple parameters can be passed in, separated by spaces.

The sample code is as follows:

file, _ := os.Create("steverocket.txt")

fmt.Fprintln(file, "Hello", name, age, "WeChat public account: CTO Plus")

Write "Hello SteveRocket 28 WeChat public account: CTO Plus" into the output.txt file. If the file exists, overwrite the content in the file. If it does not exist, create the file.

picture

For other uses of os, please refer to the article "2. Detailed explanation of os in the standard library (built-in package) in Go" by the public account CTO Plus.

6. Fprintf() function

The Fprintf() function is used to print the given parameters to the specified io.Writer interface in the specified format.

The first parameter is the io.Writer interface to be printed, the second parameter is the format string, and the following parameters are the values ​​to be printed.

Placeholders can be used in the format string to indicate the type and format of the value to be printed.

The sample code is as follows:

file2, _ := os.Create("steverocket.txt")

fmt.Fprintf(file2, "My name is %s and I am %d years old.", name, age)

// Write "My name is SteveRocket and I am 28 years old." into the steverocket.txt file. If the file already exists, the previous content will be overwritten. If it does not exist, the file will be created.

picture

7. Sprintf() function

The Sprintf() function is used to convert the given parameters into strings according to the specified format and return a new string containing these strings.

The first parameter is the format string, and the following parameters are the values ​​to be converted.

Placeholders can be used in the format string to represent the type and format of the value to be converted.

The sample code is as follows:

info := fmt.Sprintf("My name is %s and I am %d years old.", name, age)

fmt.Println(info) // My name is SteveRocket and I am 28 years old.

At the same time, you can also use this function to convert numbers into strings. Strings can be expressed in binary, octal, decimal or hexadecimal.

Format

describe

%b

Integers are displayed in binary format

%o

Integers are displayed in octal format

%d

Integers are displayed in decimal format

%x

Integers are displayed in hexadecimal format

%X

Integers are displayed in hexadecimal and capital letters.

 

Instructions

fmt.Sprintf("%d", int32(111)) // 111

fmt.Sprintf("%d", int64(111)) // 111

fmt.Sprintf("%d", 111) // 111

fmt.Sprintf("%b", 10) // 1010

Sprintf also supports float32 and float64 conversion to string

fmt.Sprintf("%f", 3.12344) // 3.123440

//Control the number of decimal places in the output

fmt.Sprintf("%.2f", 323.12344) // 323.12


 

8. Errorf() function

The Errorf() function is used to format and return an error string.

The first parameter is the format string, and the following parameters are the values ​​to be formatted.

Placeholders can be used in the format string to represent the type and format of the value to be formatted.

The sample code is as follows:

err := fmt.Errorf("An error occurred: %s, age is %d", "file not found", age)

fmt.Println(err) // An error occurred: file not found, age is 28

9. println() function

In the Go language, println() and print() are two commonly used printout functions, used to output information in the program. Their function is to print the specified parameters to the standard output (console).

The println() function prints the given arguments to standard output, adding a space between each argument and a newline character at the end. Multiple parameters can be passed in, separated by commas.

The sample code is as follows:

println("Hello", "SteveRocket", 28, 123.456, true) // Hello SteveRocket 28 +1.234560e+002 true

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

10. print() function

The print() function is used to print the given parameters to the standard output without adding a space between each parameter. Multiple parameters can be passed in, separated by commas, and the output results will not wrap.

The sample code is as follows:

print("Hello", "SteveRocket", 28, 123.456, true)// HelloSteveRocket28+1.234560e+002true

These two functions are built-in functions of the Go language and can be used directly in the program without importing any packages. They can output various types of data, including strings, numbers, Boolean values, etc. By using these two functions, developers can easily output various information in the program, including variable values, debugging information, program status, etc. This is useful for debugging and viewing the results of program execution.

It should be noted that the content output by these two functions can only be printed to the standard output (console), and the content cannot be written to a file or other output stream. If you need to write the print content to a file, you can use the related functions provided by the fmt package, such as fmt.Fprintln() and fmt.Fprintf().

The difference between println(), fmt.Println(), print() and fmt.Print()

In the Go language, println(), fmt.Println(), print() and fmt.Print() are all commonly used print output functions. There are some differences between them, as follows:

1. The difference between println() and fmt.Println()

The println() function is a function built into the Go language and can be used without importing any package; while the fmt.Println() function is a function in the fmt package and needs to be imported to use the fmt package.

The println() function adds a space between each parameter and a newline character at the end; the fmt.Println() function adds a space between each parameter and a newline character at the end.

The println() function can pass in multiple parameters, separated by commas; the fmt.Println() function can also pass in multiple parameters, separated by commas.

The parameters of the println() function can be any type of data; the parameters of the fmt.Println() function can be any type of data.

2. The difference between print() and fmt.Print()

The print() function is a function built into the Go language and can be used without importing any package; while the fmt.Print() function is a function in the fmt package and needs to be imported to use the fmt package.

The print() function does not add a space between each parameter; the fmt.Print() function adds a space between each parameter.

The print() function can pass in multiple parameters, separated by commas; the fmt.Print() function can also pass in multiple parameters, separated by commas.

The parameters of the print() function can be any type of data; the parameters of the fmt.Print() function can be any type of data.

The two pairs of functions differ mainly in the packages used and subtle differences in the output format. The println() and print() functions are built-in functions of the Go language. They are simple and convenient to use, but their functions are relatively simple and can only output to standard output. The fmt.Println() and fmt.Print() functions are functions in the fmt package, which provide more formatting options and output methods, and can output to standard output, files, or other output streams. Therefore, if you need more complex formatted output or writing content to a file, it is recommended to use the related functions provided by the fmt package.

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

Summarize

In general, by using these printout functions, developers can easily output various information in the program, including variable values, error messages, debugging information, etc. These printout functions provide different printing methods and formatting options, which can help developers quickly locate problems, verify program logic and observe program running results, improve development efficiency and debugging capabilities, and can select appropriate functions to implement printout as needed. needs.

The println() and print() functions are commonly used printout functions in the Go language, which are used to output information to the standard output in the program. They are simple to use and can conveniently output various types of data. But if you need more complex formatted output or writing content to a file, it is recommended to use the related functions provided by the fmt package.

Cloud native & microservice column
https://blog.csdn.net/zhouruifu2015/category_5704941

For more exciting news, follow my official account and learn and grow together.

picture

picture

Recommended reading:

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/133387852