Golang : Reset buffer example
There are two ways to reset a buffer that with content ( length not equal zero ). You can use either Reset()
or Truncate()
methods found in the bytes.NewBuffer()
function. The following example demonstrates how to create a buffer, check the size and capacity before and after clearing the buffer content.
package main
import (
"bytes"
"fmt"
)
func main() {
buffer := bytes.NewBuffer([]byte("abcdefghijkl"))
// convert buffer to bytes and to string for println
fmt.Println("Before reset : ", string(buffer.Bytes()))
fmt.Printf("Buffer's Length %d and capacity %d \n", len(buffer.Bytes()), cap(buffer.Bytes()))
buffer.Reset()
fmt.Println("After reset : ", string(buffer.Bytes()))
fmt.Printf("Buffer's Length %d and capacity %d \n", len(buffer.Bytes()), cap(buffer.Bytes()))
buffer2 := bytes.NewBuffer([]byte("mnopqrstuvwxyz"))
fmt.Println("Before truncate(0) : ", string(buffer2.Bytes()))
fmt.Printf("Buffer 2's Length %d and capacity %d \n", len(buffer2.Bytes()), cap(buffer2.Bytes()))
// alternate way to reset buffer
buffer2.Truncate(0)
fmt.Println("After truncate(0) : ", string(buffer2.Bytes()))
fmt.Printf("Buffer 2's Length %d and capacity %d \n", len(buffer2.Bytes()), cap(buffer2.Bytes()))
}
Output :
Before reset : abcdefghijkl
Buffer's Length 12 and capacity 32
After reset :
Buffer's Length 0 and capacity 32
Before truncate(0) : mnopqrstuvwxyz
Buffer 2's Length 14 and capacity 32
After truncate(0) :
Buffer 2's Length 0 and capacity 32
References :
https://www.socketloop.com/references/golang-bufio-reset-function-example
https://www.socketloop.com/references/golang-bytes-buffer-truncate-function-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.6k Golang : Reverse by word
+13.8k Golang : convert rune to unicode hexadecimal value and back to rune character
+36.1k Golang : How to split or chunking a file to smaller pieces?
+8.1k Golang : Configure Apache and NGINX to access your Go service example
+9.6k Golang : Detect number of active displays and the display's resolution
+21k Golang : Clean up null characters from input data
+7.8k Golang : Gomobile init produce "iphoneos" cannot be located error
+6.8k Golang : Calculate BMI and risk category
+10.8k Golang : How to transmit update file to client by HTTP request example
+7.1k Golang : Check if one string(rune) is permutation of another string(rune)
+5.8k Unix/Linux : How to open tar.gz file ?
+12.1k Golang : Simple client-server HMAC authentication without SSL example