Go 如何在文本中插入内容? 代码示范

16 min read

在 Go 中,可以使用 fmt 包中的 Print 系列函数来将文本输出到标准输出流中,也可以使用 strings 包中的 Join 函数来合并多个字符串为一个字符串。

示例代码:

package main

import (
	"fmt"
	"strings"
)

func main() {
	// 在标准输出流中插入内容
	fmt.Println("Hello, world!")
	
	// 在字符串中插入内容
	name := "Alice"
	message := fmt.Sprintf("Hello, %s!", name)
	fmt.Println(message)
	
	// 合并多个字符串为一个字符串
	words := []string{"one", "two", "three"}
	joined := strings.Join(words, ", ")
	fmt.Println(joined)
}

输出:

Hello, world!
Hello, Alice!
one, two, three