Home >Backend Development >Golang >How to Get Unicode Character Representations and Code Points in Go?

How to Get Unicode Character Representations and Code Points in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 20:56:48664browse

How to Get Unicode Character Representations and Code Points in Go?

How to Obtain Unicode Character Representations and Code Points in Go

In Go, the equivalents of Python's chr() and ord() functions for obtaining Unicode character representations and code points are straightforward conversions.

Character Conversion (chr)

To obtain a Unicode character from its code point, simply perform a type conversion from int to rune (a type alias for an integer representing a Unicode code point):

ch := rune(97)
fmt.Printf("char: %c\n", ch) // Output: char: a

Code Point Conversion (ord)

To obtain the code point corresponding to a Unicode character, perform a type conversion from rune to int:

n := int('a')
fmt.Printf("code: %d\n", n) // Output: code: 97

Note: You can also convert integer values to strings in Go, which interprets the integer as its UTF-8 encoded value:

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

This is useful for representing characters as strings, rather than runes.

Additional Considerations for Integer Conversion

It's important to note that converting a signed or unsigned integer value to a string will result in a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points will be converted to "uFFFD".

The above is the detailed content of How to Get Unicode Character Representations and Code Points in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn