Go by Example: Strings and Runes

In Go, a string is a sequence of characters and is represented by double quotes. For example:

package main

import "fmt"

func main() {
	str := "Hello, world!"
	fmt.Println(str)
}

Output:

Hello, world!

In Go, strings are immutable, meaning that you cannot modify an existing string. If you need to modify a string, you must create a new string with the desired changes.

Go also has a type called rune, which represents a Unicode code point and is essentially an alias for int32. Runes are useful for working with Unicode characters, as they allow you to work with individual characters in a string, rather than just the string as a whole.

Here’s an example of how to use runes in Go:

package main

import "fmt"

func main() {
	str := "Hello, 世界!"
	for i, r := range str {
		fmt.Printf("%d: %c\n", i, r)
	}
}

Output:

0: H
1: e
2: l
3: l
4: o
5: ,
6:  
7: 世
9: 界
10: !

In this example, we use the range keyword to iterate over the characters in str, and for each character, we print the index of the character and the character itself. Note that we use the %c format specifier to print a character, and the %d format specifier to print an integer.

By using runes, you can easily work with individual characters in a string, and can handle characters from a variety of scripts and alphabets. Whether you are working with ASCII characters or Unicode characters, strings and runes provide a convenient and flexible way to work with character data in Go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *