Equivalent to python ord (), chr () in go?

What is equivalent to python chr () and ord () in golang?

chr(97) = 'a' ord('a') = 97 
+7
go
source share
2 answers

They are supported as simple conversions :

 ch := rune(97) n := int('a') fmt.Printf("char: %c\n", ch) fmt.Printf("code: %d\n", n) 

Exit (try on the Go Playground ):

 char: a code: 97 

Note: you can also convert an integer numeric value to a string number , which basically interprets the integer value as a UTF-8 encoded value

 s := string(97) fmt.Printf("text: %s\n", s) // Output: text: a 

Converting a signed or unsigned integer value to a string type gives a string containing a representation of the UTF-8 integer. Values ​​outside of valid Unicode code points are converted to "\uFFFD" .

+13
source share

It seems that a simple uint8('a') will produce the correct result. To convert from integers to string, string(98) will suffice:

 uint8('g') // 103 string(112) // p 
+1
source share

All Articles