string Golang 将字符串转换为 io.Writer?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36302351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Golang Convert String to io.Writer?
提问by Acidic9
Is it possible to convert a string
to an io.Writer
type in Golang?
是否可以将 a 转换为Golang 中string
的io.Writer
类型?
I will be using this string in fmt.Fprintf()
but I am unable to convert the type.
我将使用这个字符串,fmt.Fprintf()
但我无法转换类型。
回答by icza
You can't write into a string
, string
s in Go are immutable.
你不能写入 a string
,string
Go 中的 s 是不可变的。
The best alternatives are the bytes.Buffer
and since Go 1.10 the faster strings.Builder
types: they implement io.Writer
so you can write into them, and you can obtain their content as a string
with Buffer.String()
and Builder.String()
, or as a byte slice with Buffer.Bytes()
.
最好的选择是bytes.Buffer
和自走1.10较快的strings.Builder
类型:他们实施io.Writer
这样你就可以写放进去,你可以得到他们的内容作为string
与Buffer.String()
和Builder.String()
,或作为与字节片Buffer.Bytes()
。
You can also have a string
as the initial content of the buffer if you create the buffer with bytes.NewBufferString()
:
string
如果您使用以下命令创建缓冲区,您还可以将 a作为缓冲区的初始内容bytes.NewBufferString()
:
s := "Hello"
buf := bytes.NewBufferString(s)
fmt.Fprint(buf, ", World!")
fmt.Println(buf.String())
Output (try it on the Go Playground):
输出(在Go Playground上试试):
Hello, World!
If you want to append a variable of type string
(or any value of string
type), you can simply use Buffer.WriteString()
(or Builder.WriteString()
):
如果你想附加一个类型的变量string
(或任何string
类型的值),你可以简单地使用Buffer.WriteString()
(或Builder.WriteString()
):
s2 := "to be appended"
buf.WriteString(s2)
Or:
或者:
fmt.Fprint(buf, s2)
Also note that if you just want to concatenate 2 string
s, you don't need to create a buffer and use fmt.Fprintf()
, you can simply use the +
operator to concatenate them:
另请注意,如果您只想连接 2 string
s,则不需要创建缓冲区并使用fmt.Fprintf()
,您只需使用+
运算符将它们连接起来即可:
s := "Hello"
s2 := ", World!"
s3 := s + s2 // "Hello, World!"
Also see: Golang: format a string without printing?
另请参阅:Golang:格式化字符串而不打印?
It may also be of interest: What's the difference between ResponseWriter.Write and io.WriteString?
回答by Sidharth J
Use bytes.Buffer
which implements the Write()
method.
使用bytes.Buffer
实现Write()
方法。
import "bytes"
writer := bytes.NewBufferString("your string")