Home > Backend Development > Golang > How Do I Convert Between Characters and Unicode Code Points in Go?

How Do I Convert Between Characters and Unicode Code Points in Go?

Susan Sarandon
Release: 2024-12-11 12:13:11
Original
912 people have browsed it

How Do I Convert Between Characters and Unicode Code Points in Go?

Finding Equivalents for Python's ord() and chr() Functions in Go

Python's ord() and chr() functions offer convenient ways to convert characters into their Unicode code points and vice versa. In Go, similar functionality is provided through simple conversions.

In Go, you can convert a Unicode code point to a character using a rune type:

ch := rune(97)
Copy after login

This assigns the Unicode code point for 'a', which is 97, to the rune variable ch.

To obtain the Unicode code point from a character, you can use an int:

n := int('a')
Copy after login

This assigns the Unicode code point for 'a' to the int variable n.

Here's an example showcasing these conversions:

package main

import (
    "fmt"
)

func main() {
    ch := rune(97)
    n := int('a')

    fmt.Printf("char: %c\n", ch)
    fmt.Printf("code: %d\n", n)
}
Copy after login

When you run this code, it will output:

char: a
code: 97
Copy after login

In addition, you can convert an integer numeric value to a string, which interprets the integer value as UTF-8 encoded:

s := string(97)
Copy after login

This assigns the character 'a' to the string variable s.

It's worth noting that converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the valid Unicode code points range are converted to "uFFFD".

The above is the detailed content of How Do I Convert Between Characters and Unicode Code Points in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template