Skip to content

strings: Builder ReadFrom permits creation of mutable strings #23083

Description

@fweimer

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions