gpt4 book ai didi

string - Golang将字符串转换为io.Writer?

转载 作者:IT老高 更新时间:2023-10-28 13:02:50 30 4
gpt4 key购买 nike

在 Golang 中是否可以将 string 转换为 io.Writer 类型?

我将在 fmt.Fprintf() 中使用此字符串,但我无法转换类型。

最佳答案

你不能写入 stringstring 在 Go 中是不可变的。

最好的选择是bytes.Buffer从 Go 1.10 开始,strings.Builder 更快类型:他们实现 io.Writer所以你可以写入它们,你可以通过 Buffer.String()string 的形式获取它们的内容和 Builder.String() , 或作为带有 Buffer.Bytes() 的字节 slice .

如果您使用 bytes.NewBufferString() 创建缓冲区,您还可以将 string 作为缓冲区的初始内容。 :

s := "Hello"
buf := bytes.NewBufferString(s)
fmt.Fprint(buf, ", World!")
fmt.Println(buf.String())

输出(在 Go Playground 上尝试):

Hello, World!

如果你想附加 string 类型的变量(或 string 类型的任何值),你可以简单地使用 Buffer.WriteString() (或 Builder.WriteString() ):

s2 := "to be appended"
buf.WriteString(s2)

或者:

fmt.Fprint(buf, s2)

还要注意,如果你只想连接 2 个 string,你不需要创建缓冲区并使用 fmt.Fprintf() ,您可以简单地使用 + 运算符来连接它们:

s := "Hello"
s2 := ", World!"

s3 := s + s2 // "Hello, World!"

另见:Golang: format a string without printing?

也可能感兴趣:What's the difference between ResponseWriter.Write and io.WriteString?

关于string - Golang将字符串转换为io.Writer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36302351/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com