Python provides two essential functions, ord() and chr(), for converting characters to their respective Unicode code points and vice versa. In Go, these conversions can be achieved through straightforward type conversions.
To obtain the Unicode code point of a character in Go, you can simply convert the character to a rune data type. The following code illustrates this:
ch := rune(97)
The result stored in the ch variable will be 97, indicating the Unicode code point for the character 'a'.
To convert a Unicode code point to its corresponding character, you can cast the code point to a rune and assign it to a string variable. For example:
n := int('a')
In this case, the n variable will contain the value 97, representing the Unicode code point for 'a'.
Go also provides a way to convert directly from an integer numeric value to a string, which interprets the value as a UTF-8 encoded character. This can be achieved as follows:
s := string(97)
In this example, the s variable will contain the string "a", representing the character associated with the Unicode code point 97.
Unlike in Python, where the chr() function can take an integer and return a character, Go uses the rune data type to represent Unicode characters internally. Runes are 32-bit integers that represent Unicode code points, allowing for the representation of a wide range of characters.
The above is the detailed content of How to Replicate Python's `ord()` and `chr()` in Go?. For more information, please follow other related articles on the PHP Chinese website!