Wednesday, 1 May 2019

Go language: strings


Strings in go are defined in double quotes.

Example
var msg string = "Hello World"

App.go
package main

import "fmt"

func main() {

 var msg string = "Hello World"

 fmt.Printf("msg : %v, type : %T\n", msg, msg)
}

Output
msg : Hello World, type : string

Get number of bytes in a string
Use built-in ‘len’ function to get the number of bytes in a string.


App.go
package main

import "fmt"

func main() {

 var msg string = "Hello World"

 fmt.Printf("msg : %v, type : %T\n", msg, msg)
 fmt.Printf("Length of msg is %v\n", len(msg))
}

Output
msg : Hello World, type : string
Length of msg is 11

Access individual byte of a string
You can access individual byte of a string using index notation.

For example, msg[0] returns the first byte of the string.


App.go
package main

import "fmt"

func main() {

 var msg string = "Hello World"

 for i := 0; i < len(msg); i++ {
  fmt.Printf("msg[%v] = %v\n", i, msg[i])
 }
}

Output
msg[0] = 72
msg[1] = 101
msg[2] = 108
msg[3] = 108
msg[4] = 111
msg[5] = 32
msg[6] = 87
msg[7] = 111
msg[8] = 114
msg[9] = 108
msg[10] = 100

String are immutable in Go
You can't change the string, once it is created.


App.go
package main

import "fmt"

func main() {

 var msg string = "Hello World"

 fmt.Printf("msg : %v", msg)

 msg[0] = 112
}

When you try to ran above program, you will endup in below error.

# command-line-arguments
./App.go:11:9: cannot assign to msg[0]




Previous                                                 Next                                                 Home

No comments:

Post a Comment