This program allows the creation of mutable strings:
package main
import (
"fmt"
"io"
"strings"
)
var global_buf []byte
type Reader struct{}
func (Reader) Read(buf []byte) (count int, err error) {
global_buf = buf
return 0, io.EOF
}
func main() {
var b strings.Builder
b.ReadFrom(Reader{})
fmt.Printf("len(global_buf): %d\n", len(global_buf))
b.WriteString("foo")
s := b.String()
fmt.Printf("string before patching: %#v\n", s)
copy(global_buf[:3], "bar")
fmt.Printf("string after patching: %#v\n", s)
}
Output is:
len(global_buf): 512
string before patching: "foo"
string after patching: "bar"
The reason why this works is that the io.Reader Read method is passed a slice which refers to the internal buffer of the builder.
This program allows the creation of mutable strings:
Output is:
The reason why this works is that the
io.Reader Readmethod is passed a slice which refers to the internal buffer of the builder.