ZetCode

Golang fmt.Fprint function

last modified May 8, 2025

This tutorial explains how to use the fmt.Fprint function in Go. We'll cover basic usage with practical examples of writing to various io.Writers.

The fmt.Fprint function writes formatted text to an io.Writer interface. It's part of Go's fmt package and is useful for writing to files, buffers, or network connections with formatting.

Unlike fmt.Print which writes to standard output, fmt.Fprint writes to any implementation of io.Writer. This makes it more flexible for various output destinations.

Basic Fprint usage

The simplest use of fmt.Fprint writes to standard output. This example demonstrates basic string writing.
Note: os.Stdout implements io.Writer interface.

basic_fprint.go
package main

import (
    "fmt"
    "os"
)

func main() {
    n, err := fmt.Fprint(os.Stdout, "Hello, World!\n")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("\nWrote %d bytes\n", n)
}

The function writes "Hello, World!" to standard output. It returns the number of bytes written and any error that occurred during writing.

Writing to a file with Fprint

fmt.Fprint can write to files since os.File implements io.Writer. This example shows file writing with error handling.

file_fprint.go
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()

    n, err := fmt.Fprint(file, "Writing to a file with Fprint\n")
    if err != nil {
        fmt.Println("Error writing to file:", err)
        return
    }
    fmt.Printf("Wrote %d bytes to file\n", n)
}

The code creates a file and writes a string to it. Always check for errors when working with files and close them properly with defer.

Writing multiple values with Fprint

fmt.Fprint can write multiple values separated by spaces. This example demonstrates writing different data types.

multiple_values.go
package main

import (
    "fmt"
    "os"
)

func main() {
    name := "Alice"
    age := 30
    height := 5.8
    
    n, err := fmt.Fprint(os.Stdout, name, " is ", age, 
        " years old and ", height, " feet tall\n")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Wrote %d bytes\n", n)
}

The function automatically converts values to strings and separates them with spaces. No newline is added unless explicitly included.

Using Fprint with bytes.Buffer

fmt.Fprint works with bytes.Buffer for in-memory string building. This example shows efficient string concatenation.

buffer_fprint.go
package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buf bytes.Buffer
    
    fmt.Fprint(&buf, "First part, ")
    fmt.Fprint(&buf, "second part, ")
    fmt.Fprint(&buf, "third part\n")
    
    fmt.Println("Buffer content:")
    fmt.Print(buf.String())
    
    fmt.Printf("Buffer length: %d bytes\n", buf.Len())
}

bytes.Buffer is efficient for building strings from multiple parts. It avoids multiple memory allocations of string concatenation.

Custom writer implementation

Any type implementing io.Writer can be used with fmt.Fprint. This example shows a custom writer implementation.

custom_writer.go
package main

import (
    "fmt"
)

type ConsoleWriter struct{}

func (cw ConsoleWriter) Write(p []byte) (n int, err error) {
    fmt.Print("Custom writer: ")
    return fmt.Print(string(p))
}

func main() {
    cw := ConsoleWriter{}
    
    n, err := fmt.Fprint(cw, "Hello from custom writer!\n")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("Wrote %d bytes via custom writer\n", n)
}

The ConsoleWriter type implements the Write method, making it compatible with fmt.Fprint. This demonstrates the flexibility of Go's interface system.

Writing to network connections

fmt.Fprint can write to network connections since they implement io.Writer. This example shows basic network writing.

network_fprint.go
package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    conn, err := net.Dial("tcp", "example.com:80")
    if err != nil {
        fmt.Println("Error connecting:", err)
        return
    }
    defer conn.Close()

    // Set deadline for write operation
    conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
    
    n, err := fmt.Fprint(conn, "GET / HTTP/1.0\r\n\r\n")
    if err != nil {
        fmt.Println("Error writing:", err)
        return
    }
    fmt.Printf("Sent %d bytes to server\n", n)
}

The example sends an HTTP request to a web server. Always handle errors and set timeouts when working with network connections.

Combining Fprint with other writers

fmt.Fprint can be used with io.MultiWriter to write to multiple destinations simultaneously. This example demonstrates this technique.

multi_writer.go
package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func main() {
    var buf bytes.Buffer
    multi := io.MultiWriter(os.Stdout, &buf)
    
    n, err := fmt.Fprint(multi, "Writing to multiple destinations\n")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Printf("Wrote %d bytes total\n", n)
    fmt.Println("Buffer content:", buf.String())
}

The output is written to both standard output and a buffer. This is useful for logging or when you need to capture output while also displaying it.

Source

Go fmt package documentation

This tutorial covered the fmt.Fprint function in Go with practical examples of writing to various io.Writer implementations.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.