How to Format Strings in Go with fmt.Sprintf

Use fmt.Sprintf with format verbs like %s and %d to build custom strings from variables in Go.

Use fmt.Sprintf with format verbs to construct strings from variables. The function returns the formatted string without printing it.

package main

import (
	"fmt"
)

func main() {
	name := "Alice"
	age := 30
	msg := fmt.Sprintf("Hello, %s! You are %d years old.", name, age)
	fmt.Println(msg)
}