JRehkemper.de

Go Snippets

Define Variables

mynumber := 1
mystring := "string"

var emptyint int
var emptystringarr []string

var sum int = 2

Conversions

Convert to String

mystring := string(var)

Convert to Integer

number, err := strconv.Atoi(mystring)

Loops

For Each Loop

for index, element := range myarr {

}

Loop Over Database Rows

for routes.Next() {
	var link string
	routes.Scan(&link)
	CheckRoute(link)
}

Read File

In one String

func readFileAsString(filename) string {
	dat, err := os.ReadFile(filename)
	if err != nil {
		log.Fatal(err)
	}
	return string(dat)
}

Split String

lines := strings.Split(fulltext, "\n")

Contains SubString

mystring := "Hello World"

if strings.Contains(mystring, "hello") {
	return true
}

String starts with

input := "This start with This"
if strings.HasPrefix(input, "This") {
  return true
}

Functions

func myfunction(parameter1 string, parameter2 int) string {
	//...
	return mystring
}

Print

fmt.Printf("%+v\n", mystruct)

Goroutines

for element := range array {
	go process(element)
} 

Limiting Go Routines

limiter := make(chan int, 8)

for element := range array {
	limiter <- 1
	go func(e element) {
		process(e)
		<- limiter
	}(element)
}

JSON

Use Null instead of 0 and empty string

By default a nil value will be encoded as "" or 0 in the json-string. You can tell go to encode it as null by adding omitempty to the declartion.

type Order struct {
	empty1 int    `json:"empty1"`           // will be 0
	empty2 int    `json:"empty2,omitempty"` // will be null
	empty3 string `json:"empty3"`           // will be ""
	empty4 string `json:"empty4,omitempty"` // will be null
}
profile picture of the author

Jannik Rehkemper

I'm an professional Linux Administrator and Hobby Programmer. My training as an IT-Professional started in 2019 and ended in 2022. Since 2023 I'm working as an Linux Administrator.