First declare, in Go language:
- exists
print
,println
does not existprintf
- exist
fmt.Println
,fmt.Println
withfmt.Printf
The following are the specific differences between print
and fmt.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.Println
the 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.Println
errors returned. If an error occurs, we write the error message to os.Stderr
and 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.Stdout
redirect to a closed or unwritable file, or similar problems, fmt.Println may return an error.