---
title: "Go"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/go
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Go

Go is a statically typed, compiled programming language designed for simplicity, efficiency, and concurrent programming. It's ideal for building fast, scalable server applications and system tools.

7 Categories21 Sections62 ExamplesPublished: 01 Sept 2023Updated: 28 Feb 2025

GoGolangProgrammingFunctionsInterfacesGoroutinesChannelsConcurrencyError Handling

[Markdown for AI(opens in a new tab)](/go/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Programming Languages](/series/programming-languages)4/4

[PreviousJavaScript](/cheatsheets/javascript)

All posts in this series (4)

Cheatsheets4

1.  [Dart](/cheatsheets/dart)
2.  [Python](/cheatsheets/python)
3.  [JavaScript](/cheatsheets/javascript)
4.  [GoYou are here](/cheatsheets/go)

Go is a statically typed, compiled programming language designed with simplicity and efficiency in mind. It excels at concurrent programming, which makes it a good fit for fast, scalable server applications and system tools.

The sections below cover Go syntax, functions, concurrency patterns, and best practices.

[Getting Started](#category-getting-started)

-   [Hello World](#section-hello-world)
-   [Variables](#section-variables)
-   [Constants](#section-constants)

[Data Types](#category-data-types)

-   [Basic Types](#section-basic-types)
-   [Arrays and Slices](#section-arrays-and-slices)
-   [Pointers](#section-pointers)

[Control Flow](#category-control-flow)

-   [Conditionals](#section-conditionals)
-   [Switch Statements](#section-switch-statements)
-   [Loops](#section-loops)

[Functions and Methods](#category-functions-and-methods)

-   [Function Definition](#section-function-definition)
-   [Lambdas and Closures](#section-lambdas-and-closures)
-   [Methods](#section-methods)

[Packages and Interfaces](#category-packages-and-interfaces)

-   [Packages](#section-packages)
-   [Exporting](#section-exporting)
-   [Interfaces](#section-interfaces)

[Concurrency](#category-concurrency)

-   [Goroutines](#section-goroutines)
-   [Channels](#section-channels)
-   [Buffered Channels and Sync](#section-buffered-channels-and-sync)

[Advanced Features](#category-advanced-features)

-   [Error Handling](#section-error-handling)
-   [Defer, Panic, and Recover](#section-defer-panic-recover)
-   [Type Conversion and Maps](#section-type-conversion-and-maps)

No commands found

Try adjusting your search term

## Getting Started

Fundamental Go concepts and basic syntax for beginners.

### Hello World

Basic Go program structure with package declaration and main function.

#### Accessibility

Ensure code examples are properly syntax-highlighted for screen readers.

#### Best Practices

-   Use fmt.Println for basic output in Go programs.
-   Keep the main function minimal and delegate to other functions.
-   Always include proper package and import declarations.

#### Common Errors

-   **Missing main function:** Every executable Go program must have a main() function in the main package.
-   **Incorrect import syntax:** Use "fmt" with double quotes, and group imports in parentheses.

#### Keywords

hello worldpackageimportsmainoutput

[Learn more](https://golang.org/doc/effective_go#hello_world)

#### Simple Hello World

A basic Go program with package declaration, import, and main function that prints a greeting.

Code

```
1package main2
3import "fmt"4
5func main() {6  fmt.Println("Hello, World!")7}
```

Execution

```
1go run main.go
```

Output

```
1Hello, World!
```

-   Every Go program must have a main package and main function.
-   The main function is the entry point of the program.

#### Multiple imports

Demonstrates grouped imports using parentheses for multiple packages.

Code

```
1package main2
3import (4  "fmt"5  "math"6)7
8func main() {9  fmt.Println("Pi is approximately", math.Pi)10}
```

Execution

```
1go run main.go
```

Output

```
1Pi is approximately 3.141592653589793
```

-   Use parentheses to group multiple imports.
-   Import order doesn't matter, but groups are conventional.

#### Using a custom function

Demonstrates defining and calling a simple function within the main package.

Code

```
1package main2
3import "fmt"4
5func greet(name string) {6  fmt.Println("Hello,", name)7}8
9func main() {10  greet("Gopher")11}
```

Execution

```
1go run main.go
```

Output

```
1Hello, Gopher
```

-   Functions are declared with the func keyword.
-   Function parameters must include their type.

### Variables

Declaring and working with variables in Go, including type inference and shorthand syntax.

#### Accessibility

Ensure variable declarations are clearly labeled.

#### Best Practices

-   Use := for short declarations inside functions.
-   Use var for package-level variables.
-   Use type inference when the type is obvious from context.

#### Common Errors

-   **Using := at package level:** Use var instead of := for package-level variables.
-   **'Unused variable' compilation error:** Either use the variable or remove it; Go requires all variables to be used.

#### Advanced Notes

-   **Multiple Assignment:** Go supports multiple assignment: a, b := 1, "hello"
-   **Blank Identifier:** Use \_ to ignore values in multi-value returns: \_, err := someFunc()

#### Keywords

variablesvardeclarationtype inferenceshorthand

[Learn more](https://golang.org/doc/effective_go#variables)

#### Variable declaration with var

Demonstrates explicit variable declaration with type specification.

Code

```
1package main2
3import "fmt"4
5func main() {6  var name string = "Alice"7  var age int = 308  fmt.Println(name, age)9}
```

Execution

```
1go run main.go
```

Output

```
1Alice 30
```

-   var keyword declares a variable with explicit type.
-   Variables must be used after declaration or compilation fails.

#### Type inference

Go infers the type from the assigned value without explicit type specification.

Code

```
1package main2
3import "fmt"4
5func main() {6  var name = "Bob"7  var count = 58  fmt.Println(name, count)9}
```

Execution

```
1go run main.go
```

Output

```
1Bob 5
```

-   Type inference makes code cleaner when the type is obvious.
-   Go still enforces strict typing at compile time.

#### Short declaration operator

Uses the shorthand := operator for quick variable declaration and initialization.

Code

```
1package main2
3import "fmt"4
5func main() {6  name := "Charlie"7  age := 258  city := "New York"9  fmt.Println(name, age, city)10}
```

Execution

```
1go run main.go
```

Output

```
1Charlie 25 New York
```

-   ':=' is only available inside functions, not at package level.
-   Cannot use := if variable already exists.

### Constants

Defining constants with const keyword, typed/untyped constants, and iota enumeration.

#### Accessibility

Ensure constant definitions are clearly explained.

#### Best Practices

-   Use constants for fixed values that shouldn't change.
-   Use iota for creating enumerations.
-   Consider grouping related constants in const blocks.

#### Common Errors

-   **Trying to reassign a constant:** Constants are immutable; declare a variable instead.
-   **iota not starting at expected value:** Remember iota starts at 0; use expressions like iota+1 if needed.

#### Advanced Notes

-   **Iota with expressions:** You can use expressions with iota: const Byte = 1 << (10 \* iota)
-   **Constant expressions:** Constants can be part of expressions evaluated at compile time.

#### Keywords

constantsconstiotatypeduntyped

[Learn more](https://golang.org/doc/effective_go#constants)

#### Simple constants

Declares constants in a grouped block using const.

Code

```
1package main2
3import "fmt"4
5const (6  Pi = 3.141597  MaxRetries = 38)9
10func main() {11  fmt.Println("Pi:", Pi)12  fmt.Println("Max retries:", MaxRetries)13}
```

Execution

```
1go run main.go
```

Output

```
1Pi: 3.141592Max retries: 3
```

-   Constants must be assigned at compile time.
-   Constants cannot be changed after creation.

#### Typed constants

Demonstrates typed constants with explicit type specification.

Code

```
1package main2
3import "fmt"4
5const (6  Status string = "active"7  Count int = 108)9
10func main() {11  fmt.Println(Status, Count)12}
```

Execution

```
1go run main.go
```

Output

```
1active 10
```

-   Typed constants are more restrictive but explicit.
-   Untyped constants are more flexible for operations.

#### Iota enumeration

Uses iota to create enum-like constants that auto-increment from 0.

Code

```
1package main2
3import "fmt"4
5const (6  Sunday iota7  Monday8  Tuesday9  Wednesday10)11
12func main() {13  fmt.Println("Monday is:", Monday)14  fmt.Println("Wednesday is:", Wednesday)15}
```

Execution

```
1go run main.go
```

Output

```
1Monday is: 12Wednesday is: 3
```

-   iota starts at 0 and increments for each const line.
-   Perfect for creating enum-like types in Go.

## Data Types

Go's type system, including basic types, arrays, slices, and pointers.

### Basic Types

Strings, integers, floats, booleans, bytes, and other numeric types.

#### Accessibility

Ensure type examples are clear and distinct.

#### Best Practices

-   Use int for most integer operations unless size matters.
-   Use float64 for floating-point arithmetic.
-   Always be explicit about types when needed for clarity.

#### Common Errors

-   **Cannot mix types in operations:** Convert types explicitly using type(value) syntax.
-   **String index returns byte, not rune:** Convert string to \[\]rune for proper Unicode handling.

#### Keywords

stringintfloatboolbyterune

[Learn more](https://golang.org/ref/spec#Numeric_types)

#### Numeric types

Demonstrates various numeric types including integers, floats, and complex numbers.

Code

```
1package main2
3import "fmt"4
5func main() {6  var intVal int = 427  var floatVal float64 = 3.148  var complexVal complex128 = 1 + 2i9
10  fmt.Println("Int:", intVal)11  fmt.Println("Float:", floatVal)12  fmt.Println("Complex:", complexVal)13}
```

Execution

```
1go run main.go
```

Output

```
1Int: 422Float: 3.143Complex: (1+2i)
```

-   Use int for most integer operations.
-   float64 is the default floating-point type.
-   complex128 supports complex number operations.

#### String and character types

Shows string, rune (Unicode), and byte types in Go.

Code

```
1package main2
3import "fmt"4
5func main() {6  var str string = "Hello, Go!"7  var char rune = 'A'8  var byteVal byte = 659
10  fmt.Println("String:", str)11  fmt.Println("Rune:", char)12  fmt.Println("Byte:", byteVal)13}
```

Execution

```
1go run main.go
```

Output

```
1String: Hello, Go!2Rune: 653Byte: 65
```

-   Strings are immutable sequences of UTF-8 bytes.
-   rune represents a Unicode code point.
-   byte is an alias for uint8.

#### Boolean type

Demonstrates the boolean type with logical operations.

Code

```
1package main2
3import "fmt"4
5func main() {6  var isActive bool = true7  var isEmpty bool = false8
9  fmt.Println("Active:", isActive)10  fmt.Println("Empty:", isEmpty)11  fmt.Println("Not empty:", !isEmpty)12}
```

Execution

```
1go run main.go
```

Output

```
1Active: true2Empty: false3Not empty: true
```

-   bool can only be true or false.
-   Use ! for logical NOT operation.

### Arrays and Slices

Fixed-size arrays, dynamic slices, and slice operations.

#### Accessibility

Ensure array and slice examples are clearly distinct.

#### Best Practices

-   Use slices instead of arrays unless size must be fixed.
-   Pre-allocate slice capacity with make for better performance.
-   Remember that slicing with \[start:end\] doesn't include the end index.

#### Common Errors

-   **Index out of range:** Check slice length with len() before accessing elements.
-   **Modifying slice affects original array:** Remember slices are views into arrays; copy if you need independence.

#### Advanced Notes

-   **Slice headers:** Slices contain a pointer, length, and capacity internally.
-   **Copy function:** Use copy(dest, src) to copy slice elements without sharing backing array.

#### Keywords

arrayslicemakeappendlengthcapacity

[Learn more](https://golang.org/blog/slices-intro)

#### Array declaration

Shows fixed-size array declaration and initialization.

Code

```
1package main2
3import "fmt"4
5func main() {6  var arr [3]int = [3]int{1, 2, 3}7  arr2 := [...]string{"a", "b", "c"}8
9  fmt.Println("Array 1:", arr)10  fmt.Println("Array 2:", arr2)11  fmt.Println("Length:", len(arr))12}
```

Execution

```
1go run main.go
```

Output

```
1Array 1: [1 2 3]2Array 2: [a b c]3Length: 3
```

-   Arrays have a fixed size specified at compile time.
-   Use ... to let the compiler infer array size from initialization.

#### Slice creation and manipulation

Demonstrates dynamic slices with append and slicing operations.

Code

```
1package main2
3import "fmt"4
5func main() {6  slice := []int{1, 2, 3, 4, 5}7  fmt.Println("Original:", slice)8
9  slice = append(slice, 6)10  fmt.Println("After append:", slice)11
12  subSlice := slice[1:4]13  fmt.Println("Sub-slice [1:4]:", subSlice)14}
```

Execution

```
1go run main.go
```

Output

```
1Original: [1 2 3 4 5]2After append: [1 2 3 4 5 6]3Sub-slice [1:4]: [2 3 4]
```

-   Slices are dynamic and can grow with append.
-   Slicing is done with \[start:end\] (end is exclusive).

#### Make and capacity

Shows how to create slices with specific capacity using make.

Code

```
1package main2
3import "fmt"4
5func main() {6  slice := make([]int, 0, 10)7  fmt.Println("Length:", len(slice), "Capacity:", cap(slice))8
9  for i := 0; i < 5; i++ {10    slice = append(slice, i)11  }12  fmt.Println("After append:", slice)13  fmt.Println("New length:", len(slice), "Capacity:", cap(slice))14}
```

Execution

```
1go run main.go
```

Output

```
1Length: 0 Capacity: 102After append: [0 1 2 3 4]3New length: 5 Capacity: 10
```

-   make creates a slice with length and optional capacity.
-   Setting capacity up front avoids reallocations as the slice grows.

### Pointers

Pointer declaration, address operator, and dereferencing.

#### Accessibility

Ensure pointer concepts are well-explained.

#### Best Practices

-   Check for nil pointers before dereferencing.
-   Use pointers for large structs to avoid copying.
-   Document functions that take pointers clearly.

#### Common Errors

-   **Panic: nil pointer dereference:** Check if pointer is nil before dereferencing with if ptr != nil.
-   **Taking address of non-addressable value:** Only addressable values can use &; literals often cannot.

#### Advanced Notes

-   **Pointers to pointers:** Go supports pointers to pointers: var pp \*\*int
-   **Function pointers:** Functions can be assigned to pointer variables for callbacks.

#### Keywords

pointeraddressdereferencenil

[Learn more](https://golang.org/doc/effective_go#pointers_vs_values)

#### Pointer basics

Demonstrates pointer declaration, address operator (&), and dereferencing (\*).

Code

```
1package main2
3import "fmt"4
5func main() {6  var x int = 427  var ptr *int = &x8
9  fmt.Println("Value of x:", x)10  fmt.Println("Address of x:", &x)11  fmt.Println("Pointer ptr:", ptr)12  fmt.Println("Dereferenced value:", *ptr)13}
```

Execution

```
1go run main.go
```

Output

```
1Value of x: 422Address of x: 0x...3Pointer ptr: 0x...4Dereferenced value: 42
```

-   & gives the address of a variable.
-   \* dereferences a pointer to get its value.

#### Pointer modification

Shows how to modify a value through a pointer.

Code

```
1package main2
3import "fmt"4
5func main() {6  x := 107  ptr := &x8
9  fmt.Println("Before:", x)10  *ptr = 2011  fmt.Println("After dereference assignment:", x)12}
```

Execution

```
1go run main.go
```

Output

```
1Before: 102After dereference assignment: 20
```

-   \*ptr = value modifies the value that ptr points to.

#### Nil pointers

Demonstrates nil pointers and nil checking.

Code

```
1package main2
3import "fmt"4
5func main() {6  var ptr *int7  fmt.Println("Nil pointer:", ptr)8  fmt.Println("Is nil:", ptr == nil)9
10  x := 511  ptr = &x12  fmt.Println("After assignment:", ptr)13  fmt.Println("Is nil:", ptr == nil)14}
```

Execution

```
1go run main.go
```

Output

```
1Nil pointer: <nil>2Is nil: true3After assignment: 0x...4Is nil: false
```

-   Uninitialized pointers are nil.
-   Always check if a pointer is nil before dereferencing to avoid panic.

## Control Flow

Conditionals, switch statements, and loops in Go.

### Conditionals

If/else statements, multiple conditions, and short statements in conditions.

#### Accessibility

Ensure conditional logic is clearly explained.

#### Best Practices

-   Avoid deeply nested if/else statements; use early returns instead.
-   Use short statements in conditions for scoped variables.
-   Keep conditions simple and readable.

#### Common Errors

-   **Missing braces:** Go requires braces even for single-line statements.
-   **Variable scope issues:** Remember variables declared in if are scoped to that block.

#### Keywords

ifelseconditionlogical operators

[Learn more](https://golang.org/doc/effective_go#if)

#### Simple if/else

Basic if/else statement for conditional execution.

Code

```
1package main2
3import "fmt"4
5func main() {6  x := 107  if x > 5 {8    fmt.Println("x is greater than 5")9  } else {10    fmt.Println("x is not greater than 5")11  }12}
```

Execution

```
1go run main.go
```

Output

```
1x is greater than 5
```

-   Braces are required in Go, even for single-statement blocks.

#### Else if chains

Chains multiple conditions with else if.

Code

```
1package main2
3import "fmt"4
5func main() {6  score := 857  if score >= 90 {8    fmt.Println("Grade: A")9  } else if score >= 80 {10    fmt.Println("Grade: B")11  } else if score >= 70 {12    fmt.Println("Grade: C")13  } else {14    fmt.Println("Grade: F")15  }16}
```

Execution

```
1go run main.go
```

Output

```
1Grade: B
```

-   else if is used for multiple conditions in sequence.

#### Short statement in condition

Declares a variable in the if condition using a short statement.

Code

```
1package main2
3import "fmt"4
5func main() {6  if x := 10; x > 5 {7    fmt.Println("x is greater than 5")8  } else if x < 5 {9    fmt.Println("x is less than 5")10  } else {11    fmt.Println("x equals 5")12  }13}
```

Execution

```
1go run main.go
```

Output

```
1x is greater than 5
```

-   Variables declared in if condition are scoped to the if/else block.

### Switch Statements

Switch/case statements, fallthrough, and type switches.

#### Accessibility

Ensure switch logic is easy to follow.

#### Best Practices

-   Use switch instead of long if/else chains.
-   Avoid fallthrough unless absolutely necessary.
-   Use type switch for working with interface{}.

#### Common Errors

-   **Unreachable code after fallthrough:** fallthrough must be the last statement in a case.

#### Keywords

switchcasedefaultfallthroughtype switch

[Learn more](https://golang.org/doc/effective_go#switch)

#### Basic switch

Basic switch statement with multiple cases and default.

Code

```
1package main2
3import "fmt"4
5func main() {6  day := 37  switch day {8  case 1:9    fmt.Println("Monday")10  case 2:11    fmt.Println("Tuesday")12  case 3:13    fmt.Println("Wednesday")14  default:15    fmt.Println("Unknown day")16  }17}
```

Execution

```
1go run main.go
```

Output

```
1Wednesday
```

-   No case value matches another; each case is independent.

#### Switch with fallthrough

Demonstrates fallthrough to execute multiple cases.

Code

```
1package main2
3import "fmt"4
5func main() {6  fruit := "apple"7  switch fruit {8  case "apple":9    fmt.Println("Red fruit")10    fallthrough11  case "cherry":12    fmt.Println("Small fruit")13  case "banana":14    fmt.Println("Yellow fruit")15  }16}
```

Execution

```
1go run main.go
```

Output

```
1Red fruit2Small fruit
```

-   fallthrough executes the next case's statements.

#### Type switch

Uses type assertion with switch to handle different types.

Code

```
1package main2
3import "fmt"4
5func main() {6  var value interface{} = "hello"7
8  switch v := value.(type) {9  case string:10    fmt.Println("String value:", v)11  case int:12    fmt.Println("Int value:", v)13  case float64:14    fmt.Println("Float value:", v)15  default:16    fmt.Println("Unknown type")17  }18}
```

Execution

```
1go run main.go
```

Output

```
1String value: hello
```

-   Type switch uses .(type) to check the underlying type.
-   Useful for working with interface{} values.

### Loops

For loops, range iteration, and while-like loops.

#### Accessibility

Ensure loop examples are clearly explained.

#### Best Practices

-   Use range for iterating over slices, arrays, and maps.
-   Use break and continue to control loop flow.
-   Keep loop logic simple and readable.

#### Common Errors

-   **Infinite loop:** Make sure the loop condition can become false, or use break.
-   **Off-by-one errors with range:** Remember range index goes from 0 to len(slice)-1.

#### Advanced Notes

-   **Labeled break:** Use labels with break to exit nested loops: OuterLoop: for ...
-   **Continue:** continue skips to the next iteration of the loop.

#### Keywords

forrangebreakcontinueloop

[Learn more](https://golang.org/doc/effective_go#for)

#### Traditional for loop

Demonstrates a traditional for loop with initialization, condition, and increment.

Code

```
1package main2
3import "fmt"4
5func main() {6  for i := 0; i < 5; i++ {7    fmt.Println("Iteration:", i)8  }9}
```

Execution

```
1go run main.go
```

Output

```
1Iteration: 02Iteration: 13Iteration: 24Iteration: 35Iteration: 4
```

-   Go only has for loops, no while; use for without condition for while behavior.

#### Range iteration

Uses range to iterate over slices with index and value.

Code

```
1package main2
3import "fmt"4
5func main() {6  fruits := []string{"apple", "banana", "cherry"}7  for idx, fruit := range fruits {8    fmt.Println(idx, "-", fruit)9  }10}
```

Execution

```
1go run main.go
```

Output

```
10 - apple21 - banana32 - cherry
```

-   range provides both index and value; use \_ to ignore either.

#### Infinite loop with break

Infinite loop using for without condition, exited with break.

Code

```
1package main2
3import "fmt"4
5func main() {6  count := 07  for {8    fmt.Println("Count:", count)9    count++10    if count >= 3 {11      break12    }13  }14  fmt.Println("Done!")15}
```

Execution

```
1go run main.go
```

Output

```
1Count: 02Count: 13Count: 24Done!
```

-   for {} creates an infinite loop; break exits early.

## Functions and Methods

Function definition, return types, lambdas, closures, and methods.

### Function Definition

Functions with parameters, return types, and multiple returns.

#### Accessibility

Ensure function signatures are clear.

#### Best Practices

-   Keep functions focused and single-purpose.
-   Return errors as the last return value.
-   Document functions with comments above the declaration.

#### Common Errors

-   **Too many return values:** Make sure the return signature matches what the function actually returns.
-   **Unused return values:** Assign to \_ to explicitly ignore values: \_, err := func().

#### Advanced Notes

-   **Variadic functions:** Use ... to accept variable number of arguments: func sum(nums ...int)
-   **Function types:** Functions are first-class; assign to variables: var f func(int) string

#### Keywords

funcparametersreturnnamed returns

[Learn more](https://golang.org/doc/effective_go#functions)

#### Simple function

Defines a simple function with parameters and a return value.

Code

```
1package main2
3import "fmt"4
5func add(a int, b int) int {6  return a + b7}8
9func main() {10  result := add(5, 3)11  fmt.Println("Sum:", result)12}
```

Execution

```
1go run main.go
```

Output

```
1Sum: 8
```

-   Parameters must include their type.
-   Return type comes after parameter list.

#### Multiple return values

Demonstrates multiple return values, commonly used for error handling.

Code

```
1package main2
3import "fmt"4
5func divide(a, b float64) (float64, error) {6  if b == 0 {7    return 0, fmt.Errorf("division by zero")8  }9  return a / b, nil10}11
12func main() {13  result, err := divide(10, 2)14  if err != nil {15    fmt.Println("Error:", err)16  } else {17    fmt.Println("Result:", result)18  }19}
```

Execution

```
1go run main.go
```

Output

```
1Result: 5
```

-   Multiple returns are wrapped in parentheses.
-   Idiomatic Go returns an error as the last return value.

#### Named return values

Uses named return values that can be returned implicitly.

Code

```
1package main2
3import "fmt"4
5func swap(a, b string) (first string, second string) {6  first = b7  second = a8  return9}10
11func main() {12  x, y := swap("hello", "world")13  fmt.Println(x, y)14}
```

Execution

```
1go run main.go
```

Output

```
1world hello
```

-   Named returns instantiate variables; return without args returns them.

### Lambdas and Closures

Anonymous functions, function literals, and closures.

#### Accessibility

Ensure closure concept is well-explained.

#### Best Practices

-   Use closures for callbacks and factory functions.
-   Be aware of closure variable captures when using concurrency.
-   Keep anonymous functions short and focused.

#### Common Errors

-   **Loop variable captured incorrectly in closures:** Copy loop variable: for \_, v := range slice { v := v; func uses v }

#### Advanced Notes

-   **Closure state:** Each function call can have its own closure state.
-   **Partial application:** Use closures to implement partial application patterns.

#### Keywords

anonymous functionclosurelambdafirst-class

[Learn more](https://golang.org/doc/effective_go#anonymous_functions)

#### Anonymous function

Demonstrates anonymous functions called immediately and assigned to variables.

Code

```
1package main2
3import "fmt"4
5func main() {6  func(name string) {7    fmt.Println("Hello,", name)8  }("Go")9
10  greet := func(name string) string {11    return "Hi, " + name12  }13  fmt.Println(greet("Gopher"))14}
```

Execution

```
1go run main.go
```

Output

```
1Hello, Go2Hi, Gopher
```

-   Anonymous functions can be called immediately or assigned.

#### Closure capturing variables

Closure captures and modifies the outer variable x.

Code

```
1package main2
3import "fmt"4
5func main() {6  x := 107  increment := func() {8    x++9  }10  increment()11  fmt.Println("x after closure:", x)12}
```

Execution

```
1go run main.go
```

Output

```
1x after closure 11
```

-   Closures capture variables by reference, not by value.

#### Higher-order function

Demonstrates higher-order functions that take functions as parameters.

Code

```
1package main2
3import "fmt"4
5func apply(f func(int) int, value int) int {6  return f(value)7}8
9func main() {10  square := func(x int) int {11    return x * x12  }13  result := apply(square, 5)14  fmt.Println("Square of 5:", result)15}
```

Execution

```
1go run main.go
```

Output

```
1Square of 5 25
```

-   Functions are first-class values in Go.

### Methods

Methods with receivers, pointer receivers, and method sets.

#### Accessibility

Ensure method concepts are clearly explained.

#### Best Practices

-   Use pointer receivers when the method modifies the receiver.
-   Use value receivers when the method only reads from the receiver.
-   Group related methods on the same type.

#### Common Errors

-   **Cannot modify receiver with value receiver:** Change to pointer receiver: func (p \*Type) Method().

#### Advanced Notes

-   **Method sets:** Only pointer receivers are in the method set of a pointer type.
-   **Methods on non-struct types:** You can define methods on any named type: type MyInt int

#### Keywords

methodreceiverpointer receivervalue receiver

[Learn more](https://golang.org/doc/effective_go#methods)

#### Value receiver method

Defines a method with a value receiver; the receiver is a copy.

Code

```
1package main2
3import "fmt"4
5type Circle struct {6  Radius float647}8
9func (c Circle) Area() float64 {10  return 3.14159 * c.Radius * c.Radius11}12
13func main() {14  circle := Circle{Radius: 5}15  fmt.Println("Area:", circle.Area())16}
```

Execution

```
1go run main.go
```

Output

```
1Area: 78.5
```

-   Value receiver receives a copy; modifications don't affect original.

#### Pointer receiver method

Uses pointer receiver to modify the receiver's state.

Code

```
1package main2
3import "fmt"4
5type Counter struct {6  Count int7}8
9func (c *Counter) Increment() {10  c.Count++11}12
13func main() {14  counter := &Counter{Count: 0}15  counter.Increment()16  counter.Increment()17  fmt.Println("Count:", counter.Count)18}
```

Execution

```
1go run main.go
```

Output

```
1Count: 2
```

-   Pointer receiver allows modification of the receiver.

#### Multiple methods on same type

Defines multiple methods on the same struct type.

Code

```
1package main2
3import "fmt"4
5type Rectangle struct {6  Width, Height float647}8
9func (r Rectangle) Area() float64 {10  return r.Width * r.Height11}12
13func (r Rectangle) Perimeter() float64 {14  return 2 * (r.Width + r.Height)15}16
17func main() {18  rect := Rectangle{Width: 5, Height: 3}19  fmt.Println("Area:", rect.Area())20  fmt.Println("Perimeter:", rect.Perimeter())21}
```

Execution

```
1go run main.go
```

Output

```
1Area: 152Perimeter: 16
```

-   Go supports methods on any named type, not just structs.

## Packages and Interfaces

Package organization, imports, exporting, and interfaces.

### Packages

Package declaration, imports, and import aliases.

#### Accessibility

Ensure package structure is clear.

#### Best Practices

-   Use clear, concise package names (usually single words).
-   Keep related functionality in the same package.
-   Avoid circular package dependencies.

#### Common Errors

-   **Package initialization loop:** Restructure packages to avoid circular dependencies.

#### Keywords

packageimportaliasnamespace

[Learn more](https://golang.org/doc/effective_go#package_names)

#### Single and grouped imports

Shows grouped import syntax with multiple standard library packages.

Code

```
1package main2
3import (4  "fmt"5  "math"6  "strings"7)8
9func main() {10  fmt.Println(strings.ToUpper("hello"))11  fmt.Println("Pi:", math.Pi)12}
```

Execution

```
1go run main.go
```

Output

```
1HELLO2Pi: 3.141592653589793
```

-   Use parentheses to group multiple imports.
-   Imports are automatically sorted alphabetically.

#### Import aliases

Uses import aliases to rename package names.

Code

```
1package main2
3import (4  fmt_pkg "fmt"5  m "math"6)7
8func main() {9  fmt_pkg.Println("Alias demo")10  fmt_pkg.Println("Pi:", m.Pi)11}
```

Execution

```
1go run main.go
```

Output

```
1Alias demo2Pi: 3.141592653589793
```

-   Aliases are useful for avoiding naming conflicts or shortening long names.

#### Package organization

Shows a package organization example with custom package structure.

Code

myapp/utils/string.go

```
1package utils2
3import "strings"4
5func Reverse(s string) string {6  runes := []rune(s)7  for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {8    runes[i], runes[j] = runes[j], runes[i]9  }10  return string(runes)11}
```

-   Package name matches directory name (usually).

### Exporting

Exported vs unexported identifiers, naming conventions.

#### Accessibility

Ensure export rules are clear.

#### Best Practices

-   Use exported names only for the public API.
-   Capitalize exported types, variables, and functions.
-   Use constructor functions for complex initialization.

#### Common Errors

-   **Cannot access unexported field:** Fields and functions must start with uppercase to be exported.

#### Keywords

exportuppercasepublicprivate

[Learn more](https://golang.org/doc/effective_go#names)

#### Exported function and variable

Shows exported (capitalized) and unexported (lowercase) identifiers.

Code

```
1package math2
3var MaxValue = 9999994
5func Add(a, b int) int {6  return a + b7}8
9func private() {10  // This function is unexported11}
```

-   Exported names start with uppercase letters.
-   Unexported names start with lowercase and are only visible within the package.

#### Exported struct and fields

Struct with exported Name field and unexported age field.

Code

```
1package person2
3type Person struct {4  Name string5  age  int6}7
8func NewPerson(name string, age int) *Person {9  return &Person{Name: name, age: age}10}
```

-   Exported struct fields are capitalized.
-   Use constructor functions (NewType) for creating instances.

### Interfaces

Interface definition, implicit implementation, type assertions.

#### Accessibility

Ensure interface concepts are well-explained.

#### Best Practices

-   Design small, focused interfaces.
-   Use interface{} sparingly; prefer explicit types when possible.
-   Use type assertions with the ok pattern to safely check types.

#### Common Errors

-   **Panic on incorrect type assertion:** Use the two-value form: value, ok := assertion.

#### Advanced Notes

-   **Interface composition:** Interfaces can embed other interfaces: type ReadWriter interface { Reader; Writer }
-   **Satisfying multiple interfaces:** A type can implicitly satisfy multiple interfaces.

#### Keywords

interfacetype assertionempty interfaceimplicit implementation

[Learn more](https://golang.org/doc/effective_go#interfaces)

#### Basic interface

Demonstrates interface definition and implicit implementation.

Code

```
1package main2
3import "fmt"4
5type Writer interface {6  Write(string) error7}8
9type File struct{}10
11func (f File) Write(content string) error {12  fmt.Println("Writing:", content)13  return nil14}15
16func SaveData(w Writer, data string) {17  w.Write(data)18}19
20func main() {21  file := File{}22  SaveData(file, "Hello World")23}
```

Execution

```
1go run main.go
```

Output

```
1Writing: Hello World
```

-   Types automatically satisfy interfaces if they implement all methods.

#### Type assertion

Uses type assertion to extract the underlying type from interface{}.

Code

```
1package main2
3import "fmt"4
5func main() {6  var val interface{} = "hello"7
8  if str, ok := val.(string); ok {9    fmt.Println("String:", str)10  } else {11    fmt.Println("Not a string")12  }13}
```

Execution

```
1go run main.go
```

Output

```
1String: hello
```

-   Type assertion panics if the type is wrong; use ok to safely check.

#### Empty interface

Uses interface{} to accept values of any type.

Code

```
1package main2
3import "fmt"4
5func Print(v interface{}) {6  fmt.Println("Value:", v)7}8
9func main() {10  Print(42)11  Print("hello")12  Print(3.14)13}
```

Execution

```
1go run main.go
```

Output

```
1Value: 422Value: hello3Value: 3.14
```

-   interface{} is the empty interface that every type implements.

## Concurrency

Goroutines, channels, and synchronization patterns.

### Goroutines

Creating goroutines with go keyword and concurrent execution.

#### Accessibility

Ensure concurrency concepts are clearly explained.

#### Best Practices

-   Use channels to communicate between goroutines.
-   Copy loop variables when launching goroutines in loops.
-   Avoid relying on sleep for synchronization; use channels or sync primitives.

#### Common Errors

-   **All goroutines are asleep:** Make the main goroutine wait for the others to complete.
-   **Race condition with loop variables:** Copy loop variable: i := i inside the loop before goroutine.

#### Advanced Notes

-   **CPU cores usage:** Use runtime.NumCPU() to get available CPU cores for goroutine scheduling.
-   **GOMAXPROCS:** Control maximum number of goroutines running simultaneously.

#### Keywords

goroutineconcurrentgo keywordlightweight

[Learn more](https://golang.org/doc/effective_go#goroutines)

#### Simple goroutine

Launches a goroutine with the go keyword for concurrent execution.

Code

```
1package main2
3import (4  "fmt"5  "time"6)7
8func printNumbers() {9  for i := 1; i <= 3; i++ {10    fmt.Println("Number:", i)11    time.Sleep(100 * time.Millisecond)12  }13}14
15func main() {16  go printNumbers()17  time.Sleep(500 * time.Millisecond)18  fmt.Println("Main done")19}
```

Execution

```
1go run main.go
```

Output

```
1Number: 12Number: 23Number: 34Main done
```

-   go launches a goroutine; main must wait for goroutines to complete.

#### Multiple goroutines

Launches multiple goroutines for concurrent task execution.

Code

```
1package main2
3import (4  "fmt"5  "time"6)7
8func worker(id int) {9  for i := 0; i < 2; i++ {10    fmt.Printf("Worker %d: task %d\n", id, i)11    time.Sleep(50 * time.Millisecond)12  }13}14
15func main() {16  for i := 1; i <= 3; i++ {17    go worker(i)18  }19  time.Sleep(200 * time.Millisecond)20}
```

Execution

```
1go run main.go
```

Output

```
1Worker 1: task 02Worker 2: task 03Worker 3: task 04Worker 1: task 15Worker 2: task 16Worker 3: task 1
```

-   Goroutines are lightweight; thousands can run concurrently.

#### Goroutine with closure

Uses closures in goroutines; copies loop variable to avoid race conditions.

Code

```
1package main2
3import (4  "fmt"5  "time"6)7
8func main() {9  for i := 1; i <= 3; i++ {10    i := i11    go func() {12      fmt.Println("Goroutine:", i)13    }()14  }15  time.Sleep(100 * time.Millisecond)16}
```

Execution

```
1go run main.go
```

Output

```
1Goroutine: 12Goroutine: 23Goroutine: 3
```

-   Copy loop variables in closures: i := i before the goroutine.

### Channels

Channel creation, sending/receiving, and channel directions.

#### Accessibility

Ensure channel operations are clearly explained.

#### Best Practices

-   Close channels from the sender side.
-   Use buffered channels to prevent deadlocks.
-   Prefer range loops over explicit receives for iterating channels.

#### Common Errors

-   **Deadlock: all goroutines asleep:** Make sure the sender and receiver are synchronized.
-   **Sending on closed channel:** Only senders should close channels; receivers cannot close.

#### Advanced Notes

-   **Channel direction:** Restrict channel direction: chan<- Type (send-only), <-chan Type (receive-only)
-   **Select statement:** Handle multiple channel operations with select.

#### Keywords

channelmakesendreceivebuffer

[Learn more](https://golang.org/doc/effective_go#channels)

#### Basic channel

Creates a channel and passes data between goroutines.

Code

```
1package main2
3import "fmt"4
5func main() {6  messages := make(chan string)7
8  go func() {9    messages <- "Hello"10  }()11
12  msg := <-messages13  fmt.Println(msg)14}
```

Execution

```
1go run main.go
```

Output

```
1Hello
```

-   <- is the send/receive operator; direction depends on context.

#### Receive pattern

Uses a buffered channel to receive multiple values.

Code

```
1package main2
3import "fmt"4
5func main() {6  results := make(chan string, 2)7
8  go func() {9    results <- "Task 1"10    results <- "Task 2"11  }()12
13  fmt.Println(<-results)14  fmt.Println(<-results)15}
```

Execution

```
1go run main.go
```

Output

```
1Task 12Task 2
```

-   make(chan Type, capacity) creates a buffered channel.

#### Ranging over channels

Uses range to iterate over channel values until close.

Code

```
1package main2
3import "fmt"4
5func main() {6  numbers := make(chan int)7
8  go func() {9    for i := 1; i <= 3; i++ {10      numbers <- i11    }12    close(numbers)13  }()14
15  for num := range numbers {16    fmt.Println(num)17  }18}
```

Execution

```
1go run main.go
```

Output

```
112233
```

-   close closes the channel; range exits when channel is closed.

### Buffered Channels and Sync

Buffered channels, channel closing, and WaitGroup synchronization.

#### Accessibility

Ensure synchronization patterns are clear.

#### Best Practices

-   Use WaitGroup for simple synchronization patterns.
-   Use channels for communicating values between goroutines.
-   Close channels only when all sends are complete.

#### Common Errors

-   **panic: send on closed channel:** Only close channels from the sender, after all sends complete.
-   **WaitGroup counter went negative:** Only call Done as many times as Add was called.

#### Advanced Notes

-   **Mutex:** Use sync.Mutex for protecting shared data: lock/unlock operations.
-   **Select with channels:** Use select to handle multiple channel operations: select { case <-ch1: }

#### Keywords

buffered channelcloseWaitGroupsyncsynchronization

[Learn more](https://golang.org/pkg/sync/)

#### Buffered channels

Buffered channel with capacity allows sending without immediate receiver.

Code

```
1package main2
3import "fmt"4
5func main() {6  messages := make(chan string, 2)7
8  messages <- "First"9  messages <- "Second"10  messages <- "Third"11
12  fmt.Println(<-messages)13  fmt.Println(<-messages)14  fmt.Println(<-messages)15}
```

Execution

```
1go run main.go
```

Output

```
1First2Second3Third
```

-   Buffered channels have a fixed capacity.
-   Sending blocks only when buffer is full.

#### Ranging over channel

Iterates over channel until it is closed.

Code

```
1package main2
3import "fmt"4
5func main() {6  ch := make(chan int, 3)7  ch <- 18  ch <- 29  ch <- 310  close(ch)11
12  for value := range ch {13    fmt.Println(value)14  }15}
```

Execution

```
1go run main.go
```

Output

```
112233
```

-   close signals that no more values will be sent.
-   range exits when the channel is closed.

#### WaitGroup for synchronization

Uses sync.WaitGroup to wait for all goroutines to complete.

Code

```
1package main2
3import (4  "fmt"5  "sync"6)7
8func main() {9  var wg sync.WaitGroup10
11  for i := 1; i <= 3; i++ {12    wg.Add(1)13    go func(id int) {14      defer wg.Done()15      fmt.Println("Worker", id)16    }(i)17  }18
19  wg.Wait()20  fmt.Println("All workers done")21}
```

Execution

```
1go run main.go
```

Output

```
1Worker 12Worker 23Worker 34All workers done
```

-   Add increments counter, Done decrements, Wait blocks until zero.

## Advanced Features

Error handling, defer/panic/recover, type conversion, and maps.

### Error Handling

Error interface, returning errors, and error checking patterns.

#### Accessibility

Ensure error patterns are clearly explained.

#### Best Practices

-   Always check for errors immediately after function calls.
-   Return errors as the last value in functions.
-   Use fmt.Errorf with %w to wrap errors with context.
-   Implement Error() for custom error types.

#### Common Errors

-   **Ignoring errors with underscore:** Never ignore errors; check and handle them explicitly.
-   **Using string errors instead of error type:** Return error type, not string; use errors.New or custom types.

#### Advanced Notes

-   **Error As:** Use errors.As to extract specific error types: errors.As(err, &target)
-   **Unwrap:** Get original error from wrapped error with Unwrap method.

#### Keywords

errorerror interfaceerror handlingerror checking

[Learn more](https://golang.org/doc/effective_go#errors)

#### Returning errors

Returns error as second value; check before using the result.

Code

```
1package main2
3import (4  "fmt"5  "errors"6)7
8func divide(a, b float64) (float64, error) {9  if b == 0 {10    return 0, errors.New("division by zero")11  }12  return a / b, nil13}14
15func main() {16  result, err := divide(10, 2)17  if err != nil {18    fmt.Println("Error:", err)19    return20  }21  fmt.Println("Result:", result)22}
```

Execution

```
1go run main.go
```

Output

```
1Result: 5
```

-   Error is returned as the last value in Go.
-   Check error immediately after the function call.

#### Custom errors

Implements custom error type with Error method.

Code

```
1package main2
3import (4  "fmt"5  "errors"6)7
8type ValidationError struct {9  Field string10  Message string11}12
13func (e ValidationError) Error() string {14  return fmt.Sprintf("%s: %s", e.Field, e.Message)15}16
17func main() {18  err := ValidationError{"Email", "Invalid format"}19  fmt.Println(err)20}
```

Execution

```
1go run main.go
```

Output

```
1Email: Invalid format
```

-   Implement Error() string method to satisfy error interface.

#### Error wrapping

Wraps errors with context while preserving the original error.

Code

```
1package main2
3import (4  "fmt"5  "errors"6)7
8func main() {9  err := errors.New("database error")10  wrapped := fmt.Errorf("failed to save user: %w", err)11  fmt.Println(wrapped)12
13  if errors.Is(wrapped, err) {14    fmt.Println("Found the original error")15  }16}
```

Execution

```
1go run main.go
```

Output

```
1failed to save user: database error2Found the original error
```

-   Use %w in fmt.Errorf to wrap errors.
-   Use errors.Is to check for specific errors.

### Defer, Panic, and Recover

Defer execution, panic for unrecoverable errors, and recover from panic.

#### Accessibility

Ensure panic patterns are clearly explained.

#### Best Practices

-   Use defer for cleanup operations like closing files.
-   Avoid panic; return errors instead for normal error conditions.
-   Use recover only inside a defer to handle panics.

#### Common Errors

-   **Defer order confusion:** Remember defers execute in LIFO order (reverse declaration order).
-   **recover returns nil outside defer:** Only call recover inside a defer; it returns nil elsewhere.

#### Advanced Notes

-   **Defer argument evaluation:** Arguments to deferred functions are evaluated immediately, not at call time.
-   **Defer with methods:** Defer can call methods: defer obj.Close()

#### Keywords

deferpanicrecovercleanup

[Learn more](https://golang.org/doc/effective_go#defer)

#### Defer for cleanup

defer runs the given code when the function exits.

Code

```
1package main2
3import "fmt"4
5func main() {6  file := "data.txt"7  fmt.Println("Opening", file)8  defer fmt.Println("Closing", file)9
10  fmt.Println("Processing file")11}
```

Execution

```
1go run main.go
```

Output

```
1Opening data.txt2Processing file3Closing data.txt
```

-   defer executes when the function returns or panics.

#### Panic usage

Uses panic for errors and recover to handle them.

Code

```
1package main2
3import "fmt"4
5func safeDivide(a, b int) int {6  if b == 0 {7    panic("division by zero")8  }9  return a / b10}11
12func main() {13  defer func() {14    if r := recover(); r != nil {15      fmt.Println("Recovered from:", r)16    }17  }()18
19  result := safeDivide(10, 0)20  fmt.Println(result)21}
```

Execution

```
1go run main.go
```

Output

```
1Recovered from: division by zero
```

-   panic stops execution; recover returns the panic value in defer.

#### Multiple defers

Defers execute in LIFO (Last In, First Out) order.

Code

```
1package main2
3import "fmt"4
5func main() {6  fmt.Println("Start")7
8  defer fmt.Println("First defer")9  defer fmt.Println("Second defer")10  defer fmt.Println("Third defer")11
12  fmt.Println("End")13}
```

Execution

```
1go run main.go
```

Output

```
1Start2End3Third defer4Second defer5First defer
```

-   Multiple defers form a stack; last defer executes first.

### Type Conversion and Maps

Type conversion syntax, maps/dictionaries, and type switching.

#### Accessibility

Ensure type conversion and maps are clearly explained.

#### Best Practices

-   Use the ok pattern to check map key existence.
-   Remember maps are unordered; don't rely on iteration order.
-   Use explicit type conversion only for compatible types.

#### Common Errors

-   **Accessing missing map key returns zero value silently:** Use the two-value form: if val, ok := m\[key\].
-   **Incompatible type conversion:** Only convert between compatible types; check at compile time.

#### Advanced Notes

-   **Map of maps:** Create nested maps: map\[string\]map\[string\]int
-   **Delete from map:** Use delete(map, key) to remove entries from a map.

#### Keywords

type conversionmapdictionarytype assertion

[Learn more](https://golang.org/doc/effective_go#maps)

#### Type conversion

Converts between compatible types using Type(value) syntax.

Code

```
1package main2
3import "fmt"4
5func main() {6  var x int32 = 427  y := int64(x)8  z := float64(x)9
10  fmt.Println("Original:", x)11  fmt.Println("To int64:", y)12  fmt.Println("To float64:", z)13}
```

Execution

```
1go run main.go
```

Output

```
1Original: 422To int64: 423To float64: 42
```

-   Type conversion is explicit; implicit conversions are not allowed.

#### Map creation and access

Creates and manipulates maps with key-value pairs.

Code

```
1package main2
3import "fmt"4
5func main() {6  scores := map[string]int{7    "Alice": 90,8    "Bob": 85,9    "Charlie": 92,10  }11
12  fmt.Println("Alice's score:", scores["Alice"])13  scores["David"] = 8814  fmt.Println("David's score:", scores["David"])15
16  if val, ok := scores["Eve"]; ok {17    fmt.Println("Eve's score:", val)18  } else {19    fmt.Println("Eve not found")20  }21}
```

Execution

```
1go run main.go
```

Output

```
1Alice's score: 902David's score: 883Eve not found
```

-   Maps are unordered; use two-value receive to check existence.

#### Iterating over maps

Iterates over map keys and values using range.

Code

```
1package main2
3import "fmt"4
5func main() {6  colors := map[string]string{7    "red":   "#FF0000",8    "green": "#00FF00",9    "blue":  "#0000FF",10  }11
12  for name, hex := range colors {13    fmt.Printf("%s: %s\n", name, hex)14  }15}
```

Execution

```
1go run main.go
```

Output

```
1red: #FF00002green: #00FF003blue: #0000FF
```

-   Maps are iterated in random order; use ordering if needed.

Was this useful?

## Tags

#Go#Golang#Programming#Functions#Interfaces#Goroutines#Channels#Concurrency#Error Handling

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Go&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo&title=Go&summary=Go%20is%20a%20statically%20typed%2C%20compiled%20programming%20language%20designed%20for%20simplicity%2C%20efficiency%2C%20and%20concurrent%20programming.%20It's%20ideal%20for%20building%20fast%2C%20scalable%20server%20applications%20and%20system%20tools.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Go%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo&text=Go "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo&title=Go "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo&t=Go "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo&media=&description=Go%20is%20a%20statically%20typed%2C%20compiled%20programming%20language%20designed%20for%20simplicity%2C%20efficiency%2C%20and%20concurrent%20programming.%20It's%20ideal%20for%20building%20fast%2C%20scalable%20server%20applications%20and%20system%20tools. "Share on Pinterest")[Email](<mailto:?subject=Go&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgo>)

## Comments

## You might also enjoy

More posts on similar topics

## [JavaScript](/cheatsheets/javascript)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Web Development
-   Frontend
-   Backend
-   Scripting

JavaScript is a high-level programming language that powers the web. It supports object-oriented, functional, and event-driven programming styles. The sections below cover JavaScript syntax and metho

#JavaScript#ES6#Web Development+3 tags

[read more](/cheatsheets/javascript)

## [Python](/cheatsheets/python)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Python
-   Scripting
-   Object Oriented
-   Web Development
-   Data Science

Python is an interpreted, high-level programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional pro

#Python#Programming#Scripting+6 tags

[read more](/cheatsheets/python)

## [Dart](/cheatsheets/dart)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Dart
-   Application Development
-   Type Safety
-   Null Safety

Dart is a statically-typed, strongly null-safe programming language designed for building fast, multi-platform applications. Created by Google, Dart ships with its own compiler, formatter, and package

#Dart#Programming#Type Safety+5 tags

[read more](/cheatsheets/dart)

## [Curl](/cheatsheets/curl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Web Development
-   APIs
-   HTTP
-   Command Line
-   Tools

Getting started with Curl cURL (client URL) is a command-line tool for transferring data using URLs. It speaks HTTP, HTTPS, FTP, SFTP, and many other protocols, which makes it the usual choice for

#Curl#HTTP#REST+3 tags

[read more](/cheatsheets/curl)

## [TOML](/cheatsheets/toml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   TOML
-   Configuration
-   Data Serialization
-   Settings

TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration file format. Designed to be minimal, readable, and unambiguous, it's used extensively in package manifests (like Cargo.toml and

#TOML#Configuration#Data Format+5 tags

[read more](/cheatsheets/toml)

## [Markdown](/cheatsheets/markdown)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Markup Language
-   Markdown
-   Documentation
-   Formatting
-   Content Creation
-   Writing

Markdown is a lightweight markup language for writing formatted content with a simple, readable syntax. It was created for writing on the web, and is now used in documentation, blogs, and note-taking

#Markdown#Formatting#Text+6 tags

[read more](/cheatsheets/markdown)

6 related posts
