The Go Language – exploring Strings – Part 4.1

Exploring Go - exploring strings in Go
Exploring Go - exploring strings in Go

Hi All,

We are continuing Go language series. In following previous articles we explored introduction to Go, wrote our first Go program and went through basic data types in Go

In this article we will discuss about string in Go. Since there are lots of things to discuss about strings, we will divide string article in multiple article series

Take away from this article

  • We will got to know details regarding Strings types in Go
    • How to represent strings in Go and respective behavior
    • String indices and substrings and demonstrations
    • Few simple programs / demonstrations

Details – Strings types

  • Strings are immutable types
    • This means as we created strings once, we can not change the content of Strings
    • Example
      • Consider – strDemo := “LIFE IS BEAUTIFUL”
      • If we try to update string data like
      • strDemo[1] := ‘L’ // we will get compile error – can not assign to strDemo[0]
    • This also means that two copies of same string shares same memory. Its safe
  • String representation in Go
    • In Go, strings are either represented in double – quotes (“”) or in backticks (“)
    • When we represent strings in double-quotes (“”), escape sequences are treated as special sequences like
      • “\n” will insert – new line
      • “\t” will insert – tab
    • But when we represent strings in backticks (“), escape sequences are treated as just characters and not the respective values

Following is the small program to represent the strings in Go and respective behavior

//Program to demonstrate strings representation on Go

// main package
package main

//importing required packages
import (
	"fmt"
)

//main function
func main() {

//When strings are enclosed in - double-quotes ("") the special sequences are treated as
	//special sequences like new lines are actual new lines as
	strNewLineDemo := "Life is beautiful \n We are very positive"
	fmt.Println(strNewLineDemo)

//When strings are enclosed in - backsticks ('') the special sequences are treated as
	//just characters like \n will be printed as \n
	_strNewLineDemo := `Life is beautiful \n We are very positive`
	fmt.Println(_strNewLineDemo)

} //main

Output of above program

PS C:\Users\Prasham\Articles\Go\BasicDataTypes> go build go_demo_3_stringtypes.go

PS C:\Users\Prasham\Articles\Go\BasicDataTypes> .\go_demo_3_stringtypes.exe

Life is beautiful    
 We are very positive

Life is beautiful \n We are very positive

Exploring Go - exploring strings in Go
fig : Exploring Go – exploring strings in Go
  • String Indices and Substrings
    • In strings, respective index returns the index-th character / byte from the string
    • Example :
      • strDemo := “LIFE IS BEAUTIFUL”
      • strDemo[0] and strDemo[5] will return 76 and 73 respectively
    • Substrings can be fetched using indices – by specifying startindex and endindex as
      • substring := strDemo[startindex : endindex]
    • Example:
      • strDemo := “LIFE IS BEAUTIFUL”
      • fmt.Println(strDemo[0:5]) => returns => LIFE
    • While fetching if index is out of range then there is error – panic as
      • fmt.Println(strDemo[0:55]) => returns runtime error => panic: runtime error: slice bounds out of range [:55] with length 17
    • We could eliminate both the indices – startindex and endindex. In this case startindex = 0 and endindex = len(string)
      • fmt.Println(strDemo[:]) => returns => LIFE IS BEAUTIFUL
    • We could either eliminate either one of the indices
      • fmt.Println(strDemo[5:]) => returns =>IS BEAUTIFUL // startindex = 5 and endindex = len(strDemo)
      • fmt.Println(strDemo[:5]) => returns =>LIFE // startindex = 0 and endindex = 5

Following is the small program to demonstrate string indices and substrings

//Program to demonstrate strings indexes and substrings

// main package
package main

//importing required packages
import (
	"fmt"
) //import

//main function
func main() {

	//Initialiizing string
	strDemo := "LIFE IS BEAUTIFUL"

	//pringing respective bytes at given index
	fmt.Println("0th and fth byte in strDemo", strDemo[0], strDemo[5])

	//Getting substring from given string
	fmt.Println(strDemo[0:5])

	//not specifying both the indices, in this case,
	//startindex = 0
	//endindex = len(string)
	fmt.Println(strDemo[:])

	//not specifying either one of the indices - end index is not specified
	//startindex = 5
	//endindex = len(string)
	fmt.Println(strDemo[5:])

	//not specifying either one of the indices - start index is not specified
	//startindex = 0
	//endindex = 5
	fmt.Println(strDemo[:5])

	//out of range index is specified - we will get an runtime error
	//panic: runtime error: slice bounds out of range [:55] with length 17
	fmt.Println(strDemo[0:55])
} //main

Output will be

0th and fth byte in strDemo 76 73
LIFE
LIFE IS BEAUTIFUL
IS BEAUTIFUL
LIFE
panic: runtime error: slice bounds out of range [:55] with length 17

goroutine 1 [running]:
main.main()

Thanks for reading!!! Feel free to discuss in case any issue / suggestions / thoughts!!!

HAVE A GREAT TIME AHEAD!!! LIFE IS BEAUTIFUL 🙂

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

2 Responses

  1. May 11, 2022

    […] The Go Language – exploring Strings – Part 4.1 […]

  2. May 29, 2022

    […] The Go Language – exploring Strings – Part 4.1 […]

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: