将字符串转换为io.Writer?(Golang技术问题)

65

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

我想在fmt.Fprintf()中使用这个字符串,但我无法进行类型转换。


4
为什么不使用fmt.Sprintf()? - Uvelichitel
3个回答

115
在Go中,无法修改string,它们是不可变的。最好的替代方案是使用bytes.Buffer或自Go 1.10起更快的strings.Builder类型:它们实现了io.Writer接口,因此您可以向它们写入内容,并且可以使用Buffer.String()Builder.String()将其作为string获取内容,或者使用Buffer.Bytes()将其作为字节片获取内容。

如果要将字符串作为缓冲区的初始内容,则可以使用bytes.NewBufferString()创建缓冲区:

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

输出结果(可在Go Playground上尝试):

Hello, World!

如果要追加一个字符串变量(或者任何类型的字符串值),你可以简单地使用 Buffer.WriteString()(或Builder.WriteString())。
s2 := "to be appended"
buf.WriteString(s2)

或者:

fmt.Fprint(buf, s2)

请注意,如果您只想连接2个字符串,则无需创建缓冲区并使用fmt.Fprintf(),您可以直接使用+运算符将它们连接起来:

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

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

另请参阅:Golang: format a string without printing?(如何在 Golang 中格式化字符串而不打印出来?)

可能也会感兴趣:ResponseWriter.Write 和 io.WriteString 之间的区别是什么?


请问您能否给我一个示例,说明如何在函数fmt.Fprintf()中使用字符串类型的变量呢? :) - Ari Seyhun

12

我看到其他回答提到了strings.Builder,但没有看到示例。因此,给您提供一个示例:

package main

import (
   "fmt"
   "strings"
)

func main() {
   b := new(strings.Builder)
   fmt.Fprint(b, "south north")
   println(b.String())
}

https://golang.org/pkg/strings#Builder


在使用strings.Builder的情况下,您也可以在构建器上使用.WriteString(s string)方法,而不是将构建器传递给fmt.Fprint - Arsham Arya

2
使用实现了Write()方法的bytes.Buffer。最初的回答。
import "bytes"

writer := bytes.NewBufferString("your string")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接