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
structandslicecan 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
ifstatements for conditional execution:if condition {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
} -
Use
forloops 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
ifstatements or thepanicandrecovermechanism.
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.