String in golang
Strings are sequence of characters with definite length and can be created by enclosing in double quotes "Hello Go" and back ticks `Hello Go`.
- A string is a sequence of characters.
- Strings are the collection of individual bytes, where each character occupy single byte.
- Characters out of the ASCII characters (can say characters from other languages) occupy more than one byte.
- A string can be created by enclosing in double quotes "Hello Go" or backticks `Hello Go`.
- The difference between double quotes and backticks is that double quotes allow escape sequences like \n (newline) and \t (tab) and parses them but backticks don't.
Example-1:
package main
import "fmt"
func main( ) {
fmt.Println(len("Hello Go"))
fmt.Println("Hello Go"[1])
fmt.Println("Hello"+" "+"Go")
}
Output:
- 8
- 101
- Hello Go
Output Explained:
- fmt.Println(len("Hello Go")) returns the length of the string "Hello Go" which is 8 characters long including space.
- fmt.Println("Hello Go"[1]) return 101 because the string can be treated as an array of characters and if "Hello Go" is an array of characters then "Hello Go"[1] returns second characters of the array as array index starts with 0, which returns 'e'. But in go lang string is a sequence of bytes so character 'e' byte value gets printed that is 101.
- For reference here is the common characters ASCII range as below.
- fmt.Println("Hello"+" "+"Go") return "Hello Go", because when '+' operator is used with strings then it performs concatenate means it merges string. so here the output will be "Hello" merged with " "(space) and then merged with "Go".
Comments
And why there are no semicolons??