Alexander Mills
Alexander Mills

Reputation: 100320

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

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?

Upvotes: -2

Views: 966

Answers (2)

Alexus1024
Alexus1024

Reputation: 523

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

Upvotes: 4

Xavier Butler
Xavier Butler

Reputation: 111

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.

Upvotes: 3

Related Questions