Golang string interpolation
16 August 2024 (Updated 16 August 2024)
On this page
fmt.Sprintf()
fmt.Sprintf()
returns the formatted string which you can assign to a variable.
package main
import "fmt"
func main() {
name := "Bob"
occupation := "developer"
experience := 5
message := fmt.Sprintf("%s is a %s with %d years of experience.", name, occupation, experience)
fmt.Println(message)
}
fmt.Printf()
fmt.Printf()
prints the formatted string directly to the standard output.
package main
import "fmt"
func main() {
language := "Go"
version := 1.18
// Directly printing the formatted string
fmt.Printf("I am learning %s version %.2f\n", language, version)
}
The specifiers for both are:
- %s – String
- %d – Decimal integer
- %f – Floating point number
- %t – Boolean
- %v – Default format for any value (a general-purpose placeholder)
- %T – Type of the value
- %x – Hexadecimal representation of an integer
- %p – Pointer address
Tagged:
Golang