Go Data Type Strings

Introduction

Go string literals can be created using double quotes "Hello, World" or backticks `Hello, World`.

The double-quoted strings cannot contain newlines and they allow special escape sequences.

For example, \n gets replaced with a newline and \t gets replaced with a tab character.

The following are some common operations on strings:

len("Hello, World") 

Finds the length of a string

"Hello, World"[1] 

Accesses a particular character in the string, in this case, the second character.

"Hello, " + World" 

Concatenates two strings together

package main//from ww w  .ja va 2 s. c  om

import "fmt" 

func main() { 
    fmt.Println(len("Hello, World")) 
    fmt.Println("Hello, World"[1]) 
    fmt.Println("Hello, " + "World") 
} 

To convert a string to a slice of bytes (and vice versa), do this:

arr  := []byte("test") 
str  := string([]byte{'t','e','s','t'}) 



PreviousNext

Related