Skip to main content

GoLang

Introduction

This cheat sheet provides a quick reference for some common Go (Golang) programming commands and concepts. Go is an open-source programming language known for its simplicity, efficiency, and concurrency support.

Basic Go Program Structure

A typical Go program has the following structure:

package main

import "fmt"

// Variables
var variableName dataType

// Functions
func functionName(param1 dataType, param2 dataType) returnType {
// Function body
return someValue
}

func main() {
// Main function body
fmt.Println("Hello, World!")
}

Variables

  • Declare and initialize a variable:

    var variableName dataType
    variableName = value
  • Declare and initialize a variable with type inference:

    variableName := value

Data Types

  • Basic data types in Go include int, float64, string, bool, and more.

  • Complex data types like struct and slice can be used for custom data structures.

Functions

  • Define a function:

    func functionName(param1 dataType, param2 dataType) returnType {
    // Function body
    return someValue
    }
  • Call a function:

    result := functionName(arg1, arg2)

Control Flow

  • Use if statements for conditional execution:

    if condition {
    // Code to execute if condition is true
    } else {
    // Code to execute if condition is false
    }
  • Use for loops for iteration:

    for i := 0; i < count; i++ {
    // Code to repeat
    }

Slices and Maps

  • Create a slice:

    sliceName := []dataType{value1, value2, ...}
  • Create a map:

    mapName := make(map[keyType]valueType)

Packages and Imports

  • Import packages for external functionality:

    import (
    "fmt"
    "math"
    )
  • Create and organize your own packages within your project.

Concurrency

  • Use Goroutines for concurrency:

    go funcName(arg)
  • Use channels for communication between Goroutines.

Error Handling

  • Handle errors using if statements or the panic and recover mechanism.

Structs

  • Define a custom data structure using struct:
    type MyStruct struct {
    Field1 dataType
    Field2 dataType
    }

Pointers

  • Use pointers to reference variables:
    var x int
    var pointerToX *int = &x

Conclusion

This cheat sheet covers some common Go (Golang) programming commands and concepts. Go is a versatile language with a growing ecosystem; refer to the official Go documentation for more in-depth information and advanced usage.