Building Strings with fmt.Sprintf
fmt.Printf prints straight to the screen. Often, though, you'd rather keep the formatted result in a string — say, to send it as a notification, save it to a database, or return it from a function. That's what fmt.Sprintf is for (S = string):
pesan := fmt.Sprintf("Pesanan #%d dikirim ke %s", 17, "Medan")
fmt.Println(pesan)
// Pesanan #17 dikirim ke Medan
That builds the string "Pesanan #17 dikirim ke Medan" ("Order #17 shipped to Medan").
The verbs are exactly the same as in Printf. The only difference: Sprintf returns a string and prints nothing.
The fmt functions follow the same naming pattern:
| Function | What it does |
|---|---|
Print | prints values as they are |
Println | prints with spaces between values + a newline |
Printf | prints with a format |
Sprint, Sprintln, Sprintf | same, but return a string |
Task
A chat app needs two helper functions. Complete both with fmt.Sprintf:
-
pesanSambutan(nama string, pesanBaru int) string(a welcome message)pesanSambutan("Budi", 3)→Halo, Budi! Kamu punya 3 pesan baru.
("Hi, Budi! You have 3 new messages.")
-
formatSaldo(saldo float64) string— the digital wallet balance is always shown with two decimal places.formatSaldo(12500.5)→Saldo dompet: Rp12500.50formatSaldo(0)→Saldo dompet: Rp0.00
("Wallet balance: Rp…")
Watch the punctuation and spaces — the tests compare the strings exactly.