How to use the strconv.UnquoteChar() function in Golang
The strconv.UnquoteChar() function
The strconv package’s UnquoteChar() function decodes the first character or byte in an escaped string or character literal represented by the string s.
Syntax
func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)
Parameters
s: This represents the quoted string.quote: This is the byte value that has to be checked.
Return value
The UnquoteChar() function returns four values:
value: This is a decoded Unicode point value of the rune type (i.e., the quote character).multibyte: This is a Boolean value that specifies whether a multibyteUTF-8representation is required for the decoded character.tail: This is a string that follows the initial quote character and is the last string.error: This is returned when the character is not syntactically valid. If the character is syntactically valid, then the error will be<nil>.
Code
The following code shows how to use the UnquoteChar() function in Golang.
// using strconv.UnquoteChar() Function in Golangpackage mainimport ("fmt""strconv")func main() {// declare variable s and assign value to itvar s = "`Golang is one of my favourite programming languages`"// declare variable value, mb, tail, err and assign value to it// represent the return valuesvalue, mb, tail, err := strconv.UnquoteChar(s, '`')// Checks if the character is syntactically validif err != nil {fmt.Println("Error:", err)}// display resultfmt.Println("value:", string(value))fmt.Println("multibyte:", mb)fmt.Println("tail:", tail)fmt.Println()// reassigning values = `\"Educative shot on UnqouteChar() function\"`// display resultfmt.Println(strconv.UnquoteChar(s, '"'))}
Explanation
- Line 4: We add the
mainpackage. - Lines 6–9: We import the necessary packages for the Golang project.
- Lines 11–33: We define the
main()function. - Line 13: We define the variable
sof the string type and assign a value to it. - Line 17: We define variables
value,mb,tail, anderr. These variables represent the return values. Next, we pass the variablesin theUnquoteChar()function and assign it to variablesvalue,mb,tail, anderr. - Line 17: We use the
ifstatement to check if the character is syntactically valid. If the condition is satisfied, the error will be displayed. - Line 24: We display the result for
value. - Line 25: We display the result for
mb. - Line 26: We display the result for
tail. - Line 30: We assign another value to variable
s. - Line 32: We pass the variable
sin theUnquoteChar()function and display the result.