goiobufferstdio

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?


Solution

  • 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.