Golang fmt.Fprintf function
last modified May 8, 2025
This tutorial explains how to use the fmt.Fprintf
function in Go.
We'll cover formatted output basics with practical examples of writing to
various io.Writer implementations.
The fmt.Fprintf function formats according to a format specifier and writes to an io.Writer. It's similar to fmt.Printf but writes to a specified writer rather than standard output.
In Go, fmt.Fprintf
is used for formatted output to files, buffers,
network connections, or any type implementing the io.Writer interface. It
returns the number of bytes written and any write error encountered.
Basic Fprintf example
The simplest use of fmt.Fprintf
writes formatted text to standard
output. This example demonstrates basic formatted printing.
Note: os.Stdout implements io.Writer, making it compatible.
package main import ( "fmt" "os" ) func main() { name := "Alice" age := 28 n, err := fmt.Fprintf(os.Stdout, "%s is %d years old\n", name, age) if err != nil { fmt.Println("Error:", err) } fmt.Printf("Wrote %d bytes\n", n) }
The example writes formatted output to standard output. It shows the number of bytes written and handles potential errors from the write operation.
Writing to a file with Fprintf
fmt.Fprintf
can write formatted text to files. This example shows
how to create a file and write formatted data to it.
package main import ( "fmt" "os" ) func main() { file, err := os.Create("output.txt") if err != nil { fmt.Println("Error creating file:", err) return } defer file.Close() items := []string{"apple", "banana", "cherry"} for i, item := range items { fmt.Fprintf(file, "Item %d: %s\n", i+1, item) } fmt.Println("Data written to file successfully") }
The example creates a file and writes formatted lines to it. Each line includes an item number and name from a slice. The file is properly closed when done.
Writing to a bytes.Buffer
fmt.Fprintf
can write to in-memory buffers. This example uses
bytes.Buffer to collect formatted output before using it.
package main import ( "bytes" "fmt" ) func main() { var buf bytes.Buffer fmt.Fprintf(&buf, "Current temperature: %.1f°C\n", 23.5) fmt.Fprintf(&buf, "Humidity: %d%%\n", 65) fmt.Println("Buffer content:") fmt.Println(buf.String()) }
The example writes formatted strings to a bytes.Buffer. The buffer collects the output which can then be used as a string or written elsewhere.
Custom writer implementation
Any type implementing io.Writer can be used with fmt.Fprintf
.
This example shows a custom writer that counts bytes written.
package main import ( "fmt" ) type ByteCounter struct { count int } func (bc *ByteCounter) Write(p []byte) (n int, err error) { bc.count += len(p) return len(p), nil } func main() { var counter ByteCounter fmt.Fprintf(&counter, "Hello, %s!\n", "world") fmt.Fprintf(&counter, "The answer is %d\n", 42) fmt.Printf("Total bytes written: %d\n", counter.count) }
The ByteCounter type implements io.Writer
by counting bytes.
Fprintf writes to our custom writer, allowing us to track total bytes written.
Formatting different data types
fmt.Fprintf
supports various format verbs for different types.
This example demonstrates formatting different data types to a writer.
package main import ( "fmt" "os" "time" ) func main() { now := time.Now() pi := 3.1415926535 fmt.Fprintf(os.Stdout, "Boolean: %t\n", true) fmt.Fprintf(os.Stdout, "Integer: %d\n", 42) fmt.Fprintf(os.Stdout, "Float: %.2f\n", pi) fmt.Fprintf(os.Stdout, "String: %s\n", "hello") fmt.Fprintf(os.Stdout, "Time: %s\n", now.Format(time.RFC3339)) fmt.Fprintf(os.Stdout, "Pointer: %p\n", &pi) }
The example shows common format verbs: %t for bool, %d for int, %f for float, %s for string, and %p for pointers. Each is written to standard output.
Error handling with Fprintf
Proper error handling is important when writing with fmt.Fprintf
.
This example demonstrates checking for write errors.
package main import ( "fmt" "os" ) func main() { // Simulate a write error by using a closed file file, err := os.Create("test.txt") if err != nil { fmt.Println("Error creating file:", err) return } file.Close() n, err := fmt.Fprintf(file, "This should fail") if err != nil { fmt.Println("Write error:", err) fmt.Println("Bytes written before error:", n) return } fmt.Println("Write successful") }
The example intentionally writes to a closed file to demonstrate error handling. Always check the error return value from Fprintf to detect write failures.
Writing to multiple writers
fmt.Fprintf
can write to multiple writers simultaneously using
io.MultiWriter. This example writes to both a file and standard output.
package main import ( "fmt" "io" "os" ) func main() { file, err := os.Create("multi_output.txt") if err != nil { fmt.Println("Error creating file:", err) return } defer file.Close() multiWriter := io.MultiWriter(os.Stdout, file) fmt.Fprintf(multiWriter, "Writing to multiple destinations\n") fmt.Fprintf(multiWriter, "This appears in both places\n") fmt.Println("Check multi_output.txt for the file content") }
The example uses io.MultiWriter
to write to both console and file
with a single Fprintf
call. This pattern is useful for logging or
tee-like output.
Source
This tutorial covered the fmt.Fprintf
function in Go with practical
examples of formatted output to various io.Writer implementations.
Author
List all Golang tutorials.