Golang Convert String to io.Writer?

huangapple go评论68阅读模式
英文:

Golang Convert String to io.Writer?

问题

在Golang中,将string转换为io.Writer类型是可能的吗?

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

英文:

Is it possible to convert a string to an io.Writer type in Golang?

I will be using this string in fmt.Fprintf() but I am unable to convert the type.

答案1

得分: 112

你不能直接向string写入内容,Go语言中的string是不可变的。

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

如果你想要将一个string作为缓冲区的初始内容,可以使用bytes.NewBufferString()创建缓冲区:

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 := "要追加的内容"
buf.WriteString(s2)

或者:

fmt.Fprint(buf, s2)

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

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

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

另请参阅:https://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265

这也可能会有兴趣:https://stackoverflow.com/questions/37863374/whats-the-difference-between-responsewriter-write-and-io-writestring/37872799#37872799

英文:

You can't write into a string, strings in Go are immutable.

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().

You can also have a string as the initial content of the buffer if you create the buffer with bytes.NewBufferString():

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

Output (try it on the 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()):

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

Or:

fmt.Fprint(buf, s2)

Also note that if you just want to concatenate 2 strings, you don't need to create a buffer and use fmt.Fprintf(), you can simply use the + operator to concatenate them:

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

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

Also see: https://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265

It may also be of interest: https://stackoverflow.com/questions/37863374/whats-the-difference-between-responsewriter-write-and-io-writestring/37872799#37872799

答案2

得分: 11

我看到另一个答案提到了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

英文:

I saw the other answer mention strings.Builder, but I didn't see an example. So here you go:

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

答案3

得分: 2

使用bytes.Buffer来实现Write()方法。

import "bytes"

writer := bytes.NewBufferString("你的字符串")
英文:

Use bytes.Buffer which implements the Write() method.

import "bytes"

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

huangapple
  • 本文由 发表于 2016年3月30日 15:31:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/36302351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定