2016-03-30 07:31
浏览 1.7k


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.

图片转代码服务由CSDN问答提供 功能建议

是否可以将 string 转换为 io.Writer

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongpu42006096 2016-03-30 07:33

    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!")

    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"


    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: Golang: format a string without printing?

    It may also be of interest: What's the difference between ResponseWriter.Write and io.WriteString?

    解决 无用
    打赏 举报

相关推荐 更多相似问题