The difference between print and fmt.Print

First declare, in Go language:

  • exists print, printlndoes not existprintf
  • exist fmt.Println, fmt.Printlnwithfmt.Printf

The following are the specific differences between printand fmt.Print:

print fmt.Print
source Go's built-in functions, no need to import packages The functions in the fmt package need to import the fmt package
Formatting ability does not support formatted output Support complex formatted output
Suggested usage scenarios Mainly used for debugging, not recommended for production environment Recommended for production environment
return value no return value Returns the number of bytes printed and possible errors
print complex objects just print out the address Print out the details of the object

Case: Use fmt.Printlnthe return value to verify whether an error occurs in the print statement:

func main() {
    
    
	n, err := fmt.Println("Hello, world!")
  
	if err != nil {
    
    
		fmt.Fprintf(os.Stderr, "Println failed: %v\n", err)
		os.Exit(1)
	}
  
	fmt.Println("Printed", n, "bytes")
}

In this example, we print "Hello, world!"and then check for fmt.Printlnerrors returned. If an error occurs, we write the error message to os.Stderrand exit the program. If no errors occurred, we print out the number of bytes written.

In most cases, fmt.Println will not return an error. But if you os.Stdoutredirect to a closed or unwritable file, or similar problems, fmt.Println may return an error.

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/131745468