How to Use the strconv.AppendQuote() Function in Golang

Golang strconv.AppendQuote() function is “used to append the double-quoted string literal representing s to dst and return the extended buffer”.

Syntax

func AppendQuote(num []byte, str string) []byte

Parameters

  1. num: A byte array (or byte slices) in which we must append the double-quoted string.
  2. s: Quote appended.

Return value

The AppendQuot returns the extended buffer after appending the double-quoted string.

Example 1: How does strconv.AppendQuote() work

package main

import (
  "fmt"
  "strconv"
)

func main() {
  x := []byte("First Quote:")
  fmt.Println()
  fmt.Println("Before AppendQuote():", string(x))

  x = strconv.AppendQuote(x, `"We are Venom!"`)
  fmt.Println()
  fmt.Println("After AppendQuote()", string(x))

  y := []byte("Second Quote:")
  fmt.Println()
  fmt.Println("Before AppendQuote():", string(y))

  y = strconv.AppendQuote(y, `"I'm Batman"`)
  fmt.Println()
  fmt.Println("After AppendQuote()", string(y))
}

Output

Before AppendQuote(): First Quote:

After AppendQuote() First Quote:"\"We are Venom!\""

Before AppendQuote(): Second Quote:

After AppendQuote() Second Quote:"\"I'm Batman\""

Example 2: Appending a Quote to a file

package main

import (
  "fmt"
  "os"
  "strconv"
)

func main() {
  // List of strings to append
  strings := []string{"Hello, Golang!",
   "I love programming", "Data is cool"}

  // Open a new file
  file, err := os.Create("quotes.txt")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }

  // Ensure the file gets closed
  defer file.Close()

  // Buffer to hold our string
  buf := make([]byte, 0, 1024)

  for _, str := range strings {
    // Clear the buffer
    buf = buf[:0]
   // Append the quoted string to the buffer
   buf = strconv.AppendQuote(buf, str)
   // Append a newline
   buf = append(buf, '\n')
   // Write the buffer to the file
   file.Write(buf)
 }

  fmt.Println("File written successfully")
}

Output

File written successfully

Appending a Quote to a file

This complex program creates a slice of strings, opens a file named “quotes.txt”, iterates over the strings, appends each quoted string into a byte slice, then appends a new line character and writes each quoted string in a new line in the file.

Finally, it prints a success message when all the strings have been written to the file.

That’s it.

Leave a Comment