ZetCode

Golang fmt.Sprintln function

last modified May 8, 2025

This tutorial explains how to use the fmt.Sprintln function in Go. We'll cover string formatting basics with practical examples of formatted output.

The fmt.Sprintln function formats its arguments into a string, adding spaces between operands and appending a newline. It returns the resulting string. This is useful for creating formatted strings without direct output.

In Go, fmt.Sprintln is part of the fmt package's string formatting functions. It's similar to fmt.Println but returns a string instead of writing to standard output.

Basic fmt.Sprintln example

The simplest use of fmt.Sprintln formats basic values into a string. This example demonstrates basic string formatting with different value types.

basic_sprintln.go
package main

import (
    "fmt"
)

func main() {
    name := "Alice"
    age := 30
    height := 5.8
    
    result := fmt.Sprintln("Name:", name, "Age:", age, "Height:", height)
    fmt.Print("Formatted string: ", result)
}

The function combines strings, integers, and floats into a single formatted string. Spaces are automatically added between operands and a newline at the end.

Formatting multiple values

fmt.Sprintln can format multiple values of different types. This example shows how it handles various data types in a single call.

multiple_values.go
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    active := true
    score := 95.5
    
    info := fmt.Sprintln("Current time:", now, "Active:", active, "Score:", score)
    fmt.Print("System info:\n", info)
}

The function formats a time value, boolean, and float along with strings. The output maintains proper spacing and includes a trailing newline.

Using with structs

fmt.Sprintln can format struct values. This example demonstrates struct formatting with default string representation.

struct_formatting.go
package main

import (
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Bob", Age: 42}
    output := fmt.Sprintln("Person details:", p)
    fmt.Print(output)
}

The struct is formatted using its default string representation. The output includes the struct field values with proper spacing and newline.

Combining with string concatenation

fmt.Sprintln results can be combined with other strings. This example shows string concatenation with formatted output.

string_concat.go
package main

import (
    "fmt"
)

func main() {
    item := "book"
    price := 29.99
    quantity := 3
    
    header := "ORDER DETAILS\n"
    details := fmt.Sprintln("Item:", item, "Price:", price, "Quantity:", quantity)
    total := fmt.Sprintf("Total: $%.2f\n", price*float64(quantity))
    
    fullOutput := header + details + total
    fmt.Print(fullOutput)
}

The formatted string from fmt.Sprintln is combined with other strings to create a complete output. This demonstrates flexible string building.

Formatting slices and arrays

fmt.Sprintln can format slice and array values. This example shows collection formatting with default representation.

slice_formatting.go
package main

import (
    "fmt"
)

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    colors := [3]string{"red", "green", "blue"}
    
    list := fmt.Sprintln("Numbers:", numbers, "Colors:", colors)
    fmt.Print("Collections:\n", list)
}

Both slice and array values are formatted with their elements shown in square brackets. The output maintains consistent spacing and includes a newline.

Custom type formatting

Types implementing the Stringer interface can customize their formatting. This example demonstrates custom string representation with fmt.Sprintln.

custom_formatting.go
package main

import (
    "fmt"
)

type Temperature float64

func (t Temperature) String() string {
    return fmt.Sprintf("%.1f°C", t)
}

func main() {
    temp := Temperature(23.5)
    output := fmt.Sprintln("Current temperature:", temp)
    fmt.Print(output)
}

The Temperature type implements the Stringer interface to provide custom formatting. fmt.Sprintln uses this custom representation.

Error handling with fmt.Sprintln

fmt.Sprintln can help format error messages. This example shows error message formatting with contextual information.

error_formatting.go
package main

import (
    "fmt"
    "os"
)

func checkFile(filename string) error {
    _, err := os.Stat(filename)
    if err != nil {
        return fmt.Errorf("file error: %v", err)
    }
    return nil
}

func main() {
    err := checkFile("missing.txt")
    if err != nil {
        msg := fmt.Sprintln("Operation failed:", err)
        fmt.Print(msg)
    }
}

The error message is formatted with additional context using fmt.Sprintln. This creates a complete error message with proper spacing and newline.

Source

Go fmt package documentation

This tutorial covered the fmt.Sprintln function in Go with practical examples of string formatting and output generation.

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.