Golang fmt.Fprintln function
last modified May 8, 2025
This tutorial explains how to use the fmt.Fprintln function in Go.
We'll cover basic usage with practical examples of formatted output operations.
The fmt.Fprintln function writes formatted text to an io.Writer. It adds spaces between operands and appends a newline. This function is versatile for writing to various output destinations.
In Go, fmt.Fprintln is part of the fmt package for formatted I/O.
It's similar to fmt.Println but writes to a specified writer
instead of standard output.
Basic Fprintln usage
The simplest use of fmt.Fprintln writes to standard output.
This example demonstrates basic formatted output with a newline.
Note: The function automatically adds spaces between arguments.
package main
import (
"fmt"
"os"
)
func main() {
// Write to standard output
fmt.Fprintln(os.Stdout, "Hello,", "World!")
// Equivalent to fmt.Println
fmt.Println("Hello,", "World!")
}
Both calls produce identical output. fmt.Println is actually
implemented using fmt.Fprintln with os.Stdout.
Writing to a file
fmt.Fprintln can write to any io.Writer, including
files. This example shows how to write formatted text to a file.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer file.Close()
fmt.Fprintln(file, "This line goes to the file")
fmt.Fprintln(file, "Multiple", "values", "joined", "with spaces")
fmt.Println("Data written to output.txt")
}
The example creates a file and writes two lines to it. Each Fprintln
call adds a newline at the end automatically.
Writing to a bytes.Buffer
fmt.Fprintln works with in-memory buffers like bytes.Buffer.
This example demonstrates string building with formatted output.
package main
import (
"bytes"
"fmt"
)
func main() {
var buf bytes.Buffer
fmt.Fprintln(&buf, "Building a string")
fmt.Fprintln(&buf, "Line", 2)
fmt.Fprintln(&buf, "Final line")
fmt.Println("Buffer content:")
fmt.Println(buf.String())
}
The bytes.Buffer accumulates the output. This is useful for
building strings efficiently or preparing output before writing.
Custom writer implementation
Any type implementing io.Writer can be used with fmt.Fprintln.
This example shows a custom writer implementation.
package main
import (
"fmt"
)
type ConsoleWriter struct{}
func (cw ConsoleWriter) Write(p []byte) (n int, err error) {
fmt.Print("Custom writer: ", string(p))
return len(p), nil
}
func main() {
cw := ConsoleWriter{}
fmt.Fprintln(cw, "This goes through our custom writer")
fmt.Fprintln(cw, "Multiple", "values", "formatted")
}
The ConsoleWriter type implements the Writer interface.
fmt.Fprintln uses it just like any standard writer.
Writing to HTTP response
fmt.Fprintln is commonly used in web servers to write HTTP responses.
This example shows HTTP response writing.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to our website!")
fmt.Fprintln(w, "Request method:", r.Method)
fmt.Fprintln(w, "Request path:", r.URL.Path)
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server starting on port 8080...")
http.ListenAndServe(":8080", nil)
}
The http.ResponseWriter implements io.Writer, making
it compatible with fmt.Fprintln. Each call adds a new line to
the response.
Error handling with Fprintln
fmt.Fprintln returns the number of bytes written and any error.
This example demonstrates proper error handling.
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("/readonly/test.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
n, err := fmt.Fprintln(file, "Test data")
if err != nil {
fmt.Println("Write error:", err)
return
}
fmt.Printf("Successfully wrote %d bytes\n", n)
}
The example checks both file creation and write operation results. Proper error handling is essential for robust file operations.
Combining with other fmt functions
fmt.Fprintln can be combined with other fmt functions for
complex output formatting. This example shows mixed usage.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprint(os.Stdout, "No newline: ")
fmt.Fprintln(os.Stdout, "This adds a newline")
fmt.Fprintf(os.Stdout, "Formatted: %d %s\n", 42, "answer")
fmt.Fprintln(os.Stdout, "Final line")
}
The example mixes Fprint, Fprintln, and Fprintf.
Each serves different formatting needs while writing to the same writer.
Source
This tutorial covered the fmt.Fprintln function in Go with practical
examples of formatted output to various writers.
Author
List all Golang tutorials.