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

Golang strconv.AppendQuoteRune() function is “used to append the single-quoted character literal, representing r (as generated by the QuoteRune() function), to dst and returns the extended buffer”.

Syntax

func AppendQuoteRune(dst []byte, r rune) []byte

Parameters

  1. dst: It is a byte array to which the single-quoted character is to be appended literal.
  2. r: It is the Rune character to be appended.

Return Value

The AppendQuoteRune() function returns the extended buffer after appending the single-quoted character.

Example 1: How to Use AppendQuoteRune() Function

package main

import (
  "fmt"
  "strconv"
)

func main() {
  x := []byte("QuoteRune:")
  fmt.Println("Orignal value before AppendQuoteRune()", string(x))
  fmt.Println()

  // Append a character (rune 108 is the Unicode of l)
  x = strconv.AppendQuoteRune(x, 87)
  fmt.Println("The new Value after AppendQuoteRune()", string(x))
  fmt.Println()

  // Append emoji
  x = strconv.AppendQuoteRune(x, '🤖')
  fmt.Println("The new Value after AppendQuoteRune()", string(x))
  fmt.Println()

  // Append emoji

  x = strconv.AppendQuoteRune(x, '🩱')
  fmt.Println("The new Value after AppendQuoteRune()", string(x))
}

Output

Orignal value before AppendQuoteRune() QuoteRune:

The new Value after AppendQuoteRune() QuoteRune:'W'

The new Value after AppendQuoteRune() QuoteRune:'W''🤖'

The new Value after AppendQuoteRune() QuoteRune:'W''🤖''🩱'

Example 2: Creating a map of runes to their names

package main

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

func main() {
  // Map of runes to their names
  runes := map[rune]string{
    '\'': "single quote",
    '"': "double quote",
    '\\': "backslash",
    '\n': "newline",
    '\r': "carriage return",
    '\t': "tab",
  }

  // Open a new file
  file, err := os.Create("runes.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, 64)

  for r, name := range runes {
    // Clear the buffer
    buf = buf[:0]

    // Append the quoted rune to the buffer
    buf = strconv.AppendQuoteRune(buf, r)

    // Append a space and the name of the rune
    buf = append(buf, ' ')
    buf = append(buf, name...)

    // Append a newline
    buf = append(buf, '\n')

    // Write the buffer to the file
    file.Write(buf)
 }

  fmt.Println("File written successfully")
}

Output

Creating a map of runes to their names

This will create a file named “runes.txt”, where each line contains a quoted rune and its name. For example, one of the lines might be the ‘\t’ tab.

That’s it!

Leave a Comment