Home >Backend Development >Golang >What are Runes and How Do They Differ from Bytes in Go?

What are Runes and How Do They Differ from Bytes in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 03:23:13111browse

What are Runes and How Do They Differ from Bytes in Go?

What is a Rune in Go?

Go employs the term "rune" as an alias for the integer data type int32. This is a bit confusing because integers are not typically used to represent characters. However, in Go, runes play a significant role in character manipulation.

Rune Literals

Rune literals in Go are represented by enclosing a single character within single quotes, such as 'a' or 'z'. These literals actually represent Unicode codepoints. For instance, 'a' corresponds to the codepoint 97.

Rune-Based Character Manipulation

The provided SwapRune function takes a rune as input and swaps its case. It uses a switch statement to handle two cases: converting lowercase characters to uppercase and vice versa.

The conditions in the switch statement, such as 'a' <= r && r <= 'z', compare the rune's value to the Unicode codepoints for 'a' and 'z'. If the rune falls within this range, it is considered a lowercase character and has its codepoint adjusted accordingly to produce the uppercase version.

Rune and String Manipulation

The SwapCase function demonstrates the use of runes in string manipulation. It employs the strings.Map function to apply the SwapRune function to each rune in the input string, effectively swapping the case of all characters.

Byte vs. Rune

While runes are used to represent Unicode codepoints, bytes represent individual bytes in a byte sequence. In ASCII, where each character is represented by a single byte, runes and bytes are interchangeable. However, in Unicode, which supports a wider range of characters, a single Unicode character can be encoded using multiple bytes. In these situations, runes provide a more accurate representation of characters than bytes.

The above is the detailed content of What are Runes and How Do They Differ from Bytes 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