How to Use strconv.AppendQuoteRuneToGraphic() Function in Golang

Golang strconv.AppendQuoteRuneToGraphic() Function is “used to append the single-quoted Go character literal that represents r (as generated by the QuoteRuneToGraphic() function) to dst and then return the extended buffer”.

Syntax

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

Parameters

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

Return value

It returns the extended buffer after appending the single-quoted character to dst.

Example 1: Using strconv.AppendQuoteRuneToGraphic()

package main

import (
  "fmt"
  "strconv"
)

func main() {
  b := []byte("QuoteRuneToGraphic:")
  fmt.Println("Before appending...")
  fmt.Println("b:", string(b))
  fmt.Println("Length(b): ", len(b))

  // Appending characters & emojis
  b = strconv.AppendQuoteRuneToGraphic(b, 97) // 'a'
  b = strconv.AppendQuoteRuneToGraphic(b, '😀')
  b = strconv.AppendQuoteRuneToGraphic(b, '🐱')
  b = strconv.AppendQuoteRuneToGraphic(b, '\n')

  fmt.Println("After appending...")
  fmt.Println("b:", string(b))
  fmt.Println("Length(b): ", len(b))
}

Output

Before appending...
b: QuoteRuneToGraphic:
Length(b): 19
After appending...
b: QuoteRuneToGraphic:'a''😀''🐱''\n'
Length(b): 38

Example 2: Complex scenario

package main

import (
  "fmt"
  "strconv"
)

func printGraphicRune(r rune) {
  buffer := []byte("Rune: ")
  buffer = strconv.AppendQuoteRuneToGraphic(buffer, r)
  fmt.Println(string(buffer))
}

func main() {
  runeList := []rune{'a', '😀', '🐱', '\n', 
                    '\t', '💩', '\u263A', ' ', 'Z'}

  fmt.Println("Before processing:")
  fmt.Println("Length of runeList: ", len(runeList))

  for _, r := range runeList {
    printGraphicRune(r)
  }

  fmt.Println("After processing:")
  fmt.Println("Length of runeList: ", len(runeList))
}

Output

Before processing:
Length of runeList: 9
Rune: 'a'
Rune: '😀'
Rune: '🐱'
Rune: '\n'
Rune: '\t'
Rune: '💩'
Rune: '☺'
Rune: ' '
Rune: 'Z'
After processing:
Length of runeList: 9

That’s it.

Leave a Comment