fmt.Print, fmt.Println, fmt.Printf, fmt.Sprintf
func Print(a ...any) (n int, err error)
func Println(a ...any) (n int, err error)
func Printf(format string, a ...any) (n int, err error)
func Sprintf(format string, a ...any) stringWrite formatted operands to standard output, or build a string with Sprintf. Choose Println, Print, or a format verb explicitly; they do not space values the same way.
| Parameter | Description |
|---|---|
a | Values to print. Println adds spaces between non-string operands and a trailing newline. |
format | A format string for Printf and Sprintf. Common verbs include %v, %+v, %#v, %d, %s, and %q. |
Returns: Print, Println, and Printf return the number of bytes written and any write error. Sprintf returns the formatted string and does not report a write error.
Errors
error— A non-nil error means the underlying writer failed. When printing to standard output this is uncommon, but the signature still returns it.
- Print does not add a space between the string "a" and the integer 1, so the output is a1. Println prints a 1.
- %#v includes a package-qualified type name. For a struct defined in package main, that name is main.cfg in this example.
- Default format %v for a struct does not include field names. Use %+v when the names matter.
package main
import "fmt"
type cfg struct {
Port int
Host string
}
func main() {
fmt.Println("a", 1)
fmt.Print("a", 1, "\n")
fmt.Printf("%d %q %v %+v %#v\n", 7, "go", cfg{80, "localhost"}, cfg{80, "localhost"}, cfg{80, "localhost"})
fmt.Println(fmt.Sprintf("%s-%d", "port", 80))
}Expected output
a 1
a1
7 "go" {80 localhost} {Port:80 Host:localhost} main.cfg{Port:80, Host:"localhost"}
port-80Related: Official fmt printing