TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang bytes.Buffer Examples (WriteString, Fprintf)

Use bytes.Buffer to write and store byte data. Call WriteString and fmt.Fprintf.
Bytes.Buffer. Often we want to build up a long sequence of bytes. With bytes.Buffer we can write bytes into a single buffer, and then convert to a string when we are done.
For performance, using bytes.Buffer is an ideal choice. And it can simplify some situations where we want to append many values together.
WriteString. A simple way to append data to a bytes.Buffer is to call WriteString. We must pass a string to this func. We can call it many times in a loop.

String: To convert the Buffer into a string, we can invoke the String() func. This string can then be printed to the console.

Golang program that uses bytes.Buffer, WriteString package main import ( "bytes" "fmt" ) func main() { // New Buffer. var b bytes.Buffer // Write strings to the Buffer. b.WriteString("ABC") b.WriteString("DEF") // Convert to a string and print it. fmt.Println(b.String()) } Output ABCDEF
Fprintf. We can use fmt.Fprintf to append things like numbers to a bytes buffer. A format string is passed as the second argument of Fprintf.

Note: For performance, using Fprintf will not be ideal—appending bytes directly, with no intermediate format step, would be faster.

Tip: We must pass a pointer reference to the bytes.Buffer as the first argument to Fprintf.

Golang program that uses Fprintf with bytes.Buffer package main import ( "bytes" "fmt" ) func main() { var b bytes.Buffer // Use Fprintf with Buffer. fmt.Fprintf(&b, "A number: %d, a string: %v\n", 10, "bird") b.WriteString("[DONE]") // Done. fmt.Println(b.String()) } Output A number: 10, a string: bird [DONE]
A summary. For appending large amounts of byte data into a single target buffer, the bytes.Buffer type is a good choice. We can use it with methods like WriteString and Fprintf.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf