在 Go 语言中,可以使用 "+" 运算符来拼接两个字符串变量。例如:
s1 := "hello"
s2 := "world"
s3 := s1 + s2
fmt.Println(s3) // 输出 "helloworld"
也可以使用 fmt.Sprintf
函数来格式化字符串并将多个变量拼接在一起:
name :="John"
age := 30
s4 := fmt.Sprintf("%s is %d years old.", name, age)
fmt.Println(s4) // 输出 "John is 30 years old."
注意,在使用 "+" 运算符拼接字符串时,如果其中一个变量是数字类型,则必须使用 strconv
包中的函数将其转换为字符串,才能与字符串变量拼接。例如:
num :=123
s5 := "The number is " + strconv.Itoa(num)
fmt.Println(s5) // 输出 "The number is 123"
此外,Go 语言还提供了一种特殊的语法,可以在字符串中使用占位符(即 %v
)来代表一个变量,并使用 Printf
函数来将多个变量拼接在一起。例如:
name :="John"
age := 30
s6 := fmt.Sprintf("%s is %d years old.", name, age)
fmt.Println(s6) // 输出 "John is 30 years old."
希望这些信息对你有帮助。