In Go, you can concatenate and format strings using the fmt
package. Here's an example:
package main
import (
"fmt"
)
func main() {
name := "John"
age := 25
// Concatenate and format strings using fmt.Sprintf()
result := fmt.Sprintf("My name is %s and I am %d years old.", name, age)
fmt.Println(result)
// Concatenate and format strings using fmt.Printf()
fmt.Printf("My name is %s and I am %d years old.\n", name, age)
// Concatenate and format strings using fmt.Println()
fmt.Println("My name is", name, "and I am", age, "years old.")
// Concatenate and format strings using fmt.Print()
fmt.Print("My name is ", name, " and I am ", age, " years old.\n")
}
In the above example, the %s
and %d
are format verbs used for string and integer formatting, respectively. The fmt.Sprintf()
function is used to concatenate and format strings, while fmt.Printf()
, fmt.Println()
, and fmt.Print()
are used to print the strings to the console.
This will output:
My name is John and I am 25 years old.
My name is John and I am 25 years old.
My name is John and I am 25 years old.
My name is John and I am 25 years old.
You can also use other format verbs like %f
for floating-point numbers, %t
for booleans, %v
for any value, etc.