rune in Go
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.
Understanding the Rune Data Type in Go
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.
Defining a Rune Variable
Rune variables in Go can be defined using the var keyword or by type inference.
var r rune = 'a'
s := rune('世')Using Runes in Strings
Runes can be used in strings to represent and manipulate individual characters.
str := "Hello, 世界"
for _, r := range str {
fmt.Printf("%c ", r)
}Performing Operations on Runes
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)Example 1: Defining and using Rune Variables
We can define and use rune variables in Go to represent Unicode code points.
For example,
- Define a rune variable named
rand assign it a character value. - Define another rune variable named
susing type inference and assign it a Unicode character. - Print the values of both rune variables to the console.
Go Program
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)
}Output
a U+0061 世 U+4E16
Example 2: Using Runes in Strings
We can use runes in strings to represent and manipulate individual characters.
For example,
- Define a string containing a mix of ASCII and Unicode characters.
- Use a
forloop with a range clause to iterate over the string, treating each character as a rune. - Print each rune character to the console.
Go Program
package main
import "fmt"
func main() {
str := "Hello, 世界"
for _, r := range str {
fmt.Printf("%c ", r)
}
}Output
H e l l o , 世 界
Example 3: Performing Operations on Runes
We can perform various operations on runes, such as converting them to integers or performing arithmetic operations.
For example,
- Define a rune variable named
r1and assign it a character value. - Define another rune variable named
r2by adding an integer tor1. - Print the resulting character of
r2to the console.
Go Program
package main
import "fmt"
func main() {
r1 := 'a'
r2 := r1 + 1
fmt.Printf("%c\n", r2)
}Output
b
Example 4: Converting Runes to Integers
We can convert runes to their integer (Unicode code point) representations and print them.
For example,
- Define a rune variable named
rand assign it a character value. - Convert the rune to its integer representation.
- Print the integer value to the console.
Go Program
package main
import "fmt"
func main() {
r := '世'
fmt.Println(int32(r))
}Output
19990