Golang Convert String to io.Writer?

StringGoWriter

String Problem Overview


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.

String Solutions


Solution 1 - String

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

Solution 2 - String

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

Solution 3 - String

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

import "bytes"

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAri SeyhunView Question on Stackoverflow
Solution 1 - StringiczaView Answer on Stackoverflow
Solution 2 - StringZomboView Answer on Stackoverflow
Solution 3 - StringSidharth JView Answer on Stackoverflow