Closed
Description
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.
Metadata
Metadata
Assignees
Type
Projects
Relationships
Development
No branches or pull requests
Activity
fweimer commentedon Dec 11, 2017
Issue #23084 is a different bug resulting in mutable strings.
bradfitz commentedon Dec 11, 2017
Also bad. Thanks for the reports! Will fix.
gopherbot commentedon Dec 11, 2017
Change https://golang.org/cl/83255 mentions this issue:
strings: fix two Builder bugs allowing mutation of strings, remove ReadFrom