dongrui6787 2016-03-30 07:31
浏览 1902
已采纳

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

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.

  • 写回答

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 Dkeil5 CT107D单片机的程序编写
  • ¥15 模拟电路求复阻抗和传递函数,请各位拍照写一下解答过程
  • ¥60 不懂得怎么运行下载来的代码
  • ¥15 CST导出3D模型图为什么和软件显示不一样?
  • ¥15 加热反应炉PLC控制系统设计(相关搜索:梯形图)
  • ¥15 python 用Dorc包报错,我的写法和网上教的是一样的但是它显示无效参数,是什么问题
  • ¥15 经过滑动平均后的一维信号还原用什么结构好呢?
  • ¥15 指定IP电脑的访问设置
  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 为什么devc++编译项目会失败啊