In this tutorial, we will learn about the rune data type in Go. We will cover the basics of defining and using rune values, including how to perform operations on runes and use them to handle Unicode characters.
The rune
data type in Go is an alias for int32
and is used to represent Unicode code points. Runes are essential for working with characters from various languages and symbol sets.
Rune variables in Go can be defined using the var
keyword or by type inference.
var r rune = 'a'
s := rune('世')
Runes can be used in strings to represent and manipulate individual characters.
str := "Hello, 世界"
for _, r := range str {
fmt.Printf("%c ", r)
}
We can perform various operations on runes, such as converting them to integers or performing arithmetic operations.
r1 := 'a'
r2 := r1 + 1
fmt.Printf("%c", r2)
We can define and use rune variables in Go to represent Unicode code points.
For example,
r
and assign it a character value.s
using type inference and assign it a Unicode character.package main
import "fmt"
func main() {
var r rune = 'a'
s := rune('世')
fmt.Printf("%c %U\n", r, r)
fmt.Printf("%c %U\n", s, s)
}
a U+0061 世 U+4E16
We can use runes in strings to represent and manipulate individual characters.
For example,
for
loop with a range clause to iterate over the string, treating each character as a rune.package main
import "fmt"
func main() {
str := "Hello, 世界"
for _, r := range str {
fmt.Printf("%c ", r)
}
}
H e l l o , 世 界
We can perform various operations on runes, such as converting them to integers or performing arithmetic operations.
For example,
r1
and assign it a character value.r2
by adding an integer to r1
.r2
to the console.package main
import "fmt"
func main() {
r1 := 'a'
r2 := r1 + 1
fmt.Printf("%c\n", r2)
}
b
We can convert runes to their integer (Unicode code point) representations and print them.
For example,
r
and assign it a character value.package main
import "fmt"
func main() {
r := '世'
fmt.Println(int32(r))
}
19990