How to implement Read() on a strings.Builder in Golang

246 views Asked by At

I have this:

type StrangBuilda struct {
    strings.Builder
}

func (s StrangBuilda) Read(b []byte) (int, error) { 
    
}

because strings.Builder doesn't implement Read() and I want to

_, err := io.Copy(l.File, b)

because when I pass a strings.Builder b ^^. It says:

Cannot use 'b' (type *strings.Builder) as the type Reader Type does not implement 'Reader' as some methods are missing: Read(p []byte) (n int, err error)

any chance we can get at the buffer of the strings.Builder or maybe have to create an entire wrapper?

2

There are 2 answers

5
Xavier Butler On BEST ANSWER

any chance we can get at the buffer of the strings.Builder

We cannot get at the buffer of the strings.Builder. We must call the String() method to access the data. That's OK because the returned string references the strings.Builder buffer. There is no copy or allocation.

or maybe have to create an entire wrapper?

Yes, we must create a wrapper to convert a strings.Builder to an io.Reader The strings package provides us with that wrapper, strings.Reader. Here is the code we use to get an io.Reader from a strings.Builder:

  r := strings.NewReader(sb.String()) // sb is the strings.Builder.
5
Alexus1024 On

It looks like your approach is using strings.Builder incorrectly. You have these options, though:

  1. Complete writing into Builder before using its contents with strings.NewReader(builder.String()). This operation will not allocate the second string.
    (io.Copy(l.File, strings.NewReader(b.String()))
  2. Replace Builder with bytes.Buffer.
    It has a different idea, but implements both io.Reader and io.Writer interfaces

Maybe you can also benefit from the io.WriteString(writer, string) helper