Golang : Convert(cast) string to rune and back to string example
Tutorial on how how to convert a string to rune type and back to string. Dealing with rune can be confusing sometimes because single quotes and double quotes can have different meaning in Golang. This example code below is pretty straightforward and ... is self explanatory.
Here you go!
package main
import (
"fmt"
"regexp/syntax"
)
func main() {
str := []rune("beta") // use rune slice
acharacter := rune('a') // use single quote, instead of double quote
onerune := rune('吃')
fmt.Printf("%v \n", string(str)) // convert back to string
fmt.Printf("%v \n", string(acharacter)) // convert back to string
fmt.Printf("%v \n", string(onerune)) // convert back to string
// there are times when accessing str is not acceptable because
// it is a slice. Therefore, you just have to reference the first
// element
// for example :
ok := syntax.IsWordChar(str[0]) // won't work without [0]
fmt.Printf("%v is a word ? : %v \n", string(str), ok)
}
Output :
beta
a
吃
beta is a word ? : true
See also : Golang : convert rune to integer value
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.2k Python : Delay with time.sleep() function example
+30.7k Golang : Calculate percentage change of two values
+11.1k Golang : Post data with url.Values{}
+13.3k Golang : reCAPTCHA example
+18.1k Golang : How to get hour, minute, second from time?
+14.2k Golang : How to determine if user agent is a mobile device example
+12k Golang : Get month name from date example
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+12k Golang : List running EC2 instances and descriptions
+6.7k Golang : Pat multiplexer routing example
+13.2k Golang : Read from buffered reader until specific number of bytes
+5.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents