Home > Backend Development > Golang > Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?

Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?

Barbara Streisand
Release: 2024-12-27 20:12:32
Original
618 people have browsed it

Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?

Why Range Over String Returns Runes, Byte by Index

According to the Go documentation and our own tests, when ranging over a string, the obtained elements are of type rune, whereas indexing into the string using str[index] yields bytes.

The core reason for this distinction stems from the definition of the string type. A string represents a sequence of bytes, and accessing individual bytes is possible through indexing.

On the other hand, the range clause is used in the for statement, It allows traversing Unicode code points in a string. Starting at 0 byte index, the iteration will return the first byte index of each UTF-8 encoded code point, and the corresponding code point value (rune type).

If you wish to iterate over the bytes in the string instead of code points, there are a few options:

  • Use a regular for loop to iterate over the indices from 0 to len(s)-1 .
  • Use for i, b := range []byte(s) to convert the string into a byte slice, and then iterate over the bytes.

These alternatives provide direct access to bytes without sacrificing code readability.

The above is the detailed content of Why Does Ranging Over a String in Go Return Runes, While Indexing Returns Bytes?. 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