Fragment Description:

Using bytes.Buffer.Reset() by J.Mercl func (*Buffer) Bytes func (b *Buffer) Bytes() []byte The Bytes() returns a slice of the contents of the unread portion of the buffer; len(b.Bytes()) == b.Len().
If the caller changes the contents of the returned slice, the contents of the buffer will change provided there are no intervening method calls on the Buffer.


Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:35

/* ... <== see fragment description ... */

package main

import (

func main() {
    var output []byte
    input_1 := []rune{'f', 'o', 'o'}
    input_2 := []rune{'b', 'a', 'r'}
    var buf bytes.Buffer
    var bytes []byte
    for _, r := range input_1 {
        bytes = make([]byte, utf8.RuneLen(r))
        // sign: EncodeRune(p []byte, r rune) int
        // EncodeRune writes into p (which must be large enough) the UTF-8 encoding
        // of
        // the rune.
        utf8.EncodeRune(bytes, r)
    // sign: (b *Buffer) Bytes() []byte
    // output is a slice of the contents of the unread portion of buf
    output = buf.Bytes()
    fmt.Println("1- output:", string(output))
    // Reset resets the buffer so it has no content. buf.Reset() is the same as
    // b.Truncate(0).
    for _, r := range input_2 {
        bytes = make([]byte, utf8.RuneLen(r))
        utf8.EncodeRune(bytes, r)
    fmt.Println("2- output:", string(output))

/* Expected Output:
1- output: foo
2- output: bar