Skip to content
DevNursery.com - New Web Developer Docs
GitHub

Golang

Go, often referred to as Golang, is a statically typed, compiled programming language known for its simplicity and efficiency. In this section, we’ll explore the fundamental aspects of Go’s syntax, including variables, data types, control structures, functions, and more.

1. Hello, World!

Let’s start with a simple “Hello, World!” program in Go:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
  • package main: Every Go program must start with a main package, and the main function is the entry point of the program.
  • import "fmt": We import the “fmt” package, which provides basic input/output functionality.
  • fmt.Println("Hello, World!"): This line prints “Hello, World!” to the console.

2. Variables and Data Types

Declaring Variables

In Go, you can declare variables using the var keyword:

var age int
age = 30

Alternatively, you can use a short variable declaration:

name := "Alice"

Constants

Constants in Go are declared using the const keyword:

const pi = 3.14159265359

Basic Data Types

Go has several basic data types:

  • int: Integer type (e.g., int, int8, int16, int32, int64)
  • float64: Floating-point numbers
  • string: String type
  • bool: Boolean type
  • byte: Alias for uint8
  • rune: Alias for int32, representing a Unicode code point

3. Control Structures

Conditional Statements (if, else, switch)

if x > 10 {
    fmt.Println("x is greater than 10")
} else if x == 10 {
    fmt.Println("x is equal to 10")
} else {
    fmt.Println("x is less than 10")
}
switch day {
case "Monday":
    fmt.Println("It's Monday")
case "Tuesday":
    fmt.Println("It's Tuesday")
default:
    fmt.Println("It's some other day")
}

Loops (for)

for i := 0; i < 5; i++ {
    fmt.Println(i)
}
names := []string{"Alice", "Bob", "Charlie"}
for _, name := range names {
    fmt.Println(name)
}

4. Functions

Defining Functions

func add(a, b int) int {
    return a + b
}

Function Arguments and Return Values Go functions can take multiple arguments and return multiple values:

func calculate(x, y int) (int, int) {
    sum := x + y
    diff := x - y
    return sum, diff
}

Variadic Functions

A variadic function accepts a variable number of arguments:

func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

Anonymous Functions (Closures)

You can define anonymous functions (closures) in Go:

func main() {
    add := func(a, b int) int {
        return a + b
    }
    result := add(3, 5)
    fmt.Println(result)
}

5. Packages and Imports

Creating Packages

Go programs are organized into packages. You can create your own packages by placing related Go files in the same directory.

Importing Packages

You import packages at the beginning of your Go files to use their functionality:

import "fmt"
import "math"

Or use parentheses to import multiple packages:

import (
    "fmt"
    "math"
)

6. Structs and Methods

Defining Structs

A struct is a composite data type that groups together variables under a single name:

type Person struct {
    Name string
    Age  int
}

Methods on Structs

You can define methods associated with structs:

func (p Person) SayHello() {
    fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.Name, p.Age)
}

7. Pointers

Declaring Pointers

You can declare pointers using the * symbol:

var x int
var ptr *int
ptr = &x

Using Pointers

Pointers allow you to modify the value at the memory address they point to:

*ptr = 42 // x is now 42

8. Error Handling

Go encourages explicit error handling. Functions that may produce errors typically return two values: the result and an error.

result, err := someFunction()
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

9. Concurrency

Go has built-in support for concurrency through goroutines and channels. Goroutines are lightweight threads of execution, and channels are used for communication between goroutines.

go func() {
    // Code to run concurrently
}()

10. Defer, Panic, and Recover

  • defer: Used to schedule a function call to be run after the current function returns.
  • panic: Used to raise a runtime error.
  • recover: Used to catch and handle panics.

11. Interfaces

Interfaces define behavior that types can implement. Go uses interfaces to achieve polymorphism.

type Shape interface {
    Area() float64
    Perimeter() float64
}

GO CLI

1. Installing Go

Before you can use Go CLI commands, you need to install the Go programming language on your system. You can download the official installer for your operating system from the Go Downloads page. Follow the installation instructions for your platform.

2. Understanding the GOPATH

Go uses a workspace directory called GOPATH to manage your Go projects and packages. It typically resides in your home directory. Make sure to set your GOPATH environment variable correctly.

export GOPATH=$HOME/go

3. Running Go Code

To run a Go program, use the go run command followed by the name of the Go source file:

go run main.go

This command compiles and executes the Go code in the specified file.

  1. Compiling Go Code You can compile Go code using the go build command. It generates an executable file that you can run later.
go build main.go

This command creates an executable file with the same name as the package’s directory or the specified output file.

./main

5. Managing Packages

Installing Packages Go uses the go get command to download and install packages. Simply provide the import path of the package you want to install:

go get github.com/package-name

This command fetches the package from the repository and installs it in your workspace.

Updating Packages

To update packages to their latest versions, use the go get -u command:

go get -u github.com/package-name

This command updates the specified package and its dependencies to their latest versions.

Removing Packages

If you want to remove a package from your workspace, use the go clean command followed by the -i flag and the import path of the package:

go clean -i github.com/package-name

Listing Installed Packages

To list all the installed packages in your workspace, use the go list command:

go list ...

The … pattern lists all packages in your workspace.

6. Conclusion

Using Go CLI commands, you can easily run, compile, and manage packages in your Go projects. Understanding these commands is essential for developing and maintaining Go applications effectively. Explore Go’s documentation for more advanced features and options.

Go Tricks

Arrays

TipPurposeSyntaxExampleRequired Package
1Declare an arrayvar arr [size]typevar numbers [5]intNone
2Initialize an arrayarr := [size]type{values}arr := [3]int{1, 2, 3}None
3Access an elementarr[index]value := arr[0]None
4Update an elementarr[index] = newValuearr[1] = 42None
5Get the lengthlen(arr)length := len(arr)None
6Iterate using a loopfor index, value := range arr { }for i, v := range arr { }None
7Slice an arrayarr[start:end]subarr := arr[1:4]None
8Append to a sliceslice = append(slice, values...)slice = append(slice, 4, 5)None
9Copy slicescopy(dest, source)copy(newArr, arr)None
10Check if an element existsIterate or use a mapIterate or use a mapNone
11Find the maximum elementIterate and compareIterate and compareNone
12Find the minimum elementIterate and compareIterate and compareNone
13Sort in ascending ordersort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] })"sort"
14Sort in descending ordersort.Slice(arr, func(i, j int) bool { return arr[i] > arr[j] })sort.Slice(arr, func(i, j int) bool { return arr[i] > arr[j] })"sort"
15Search for an elementIterate or use a mapIterate or use a mapNone
16Filter elementsCreate a new sliceCreate a new sliceNone
17Map elementsCreate a new slice with mapped valuesCreate a new slice with mapped valuesNone
18Reverse an array/sliceIterate and swap elementsIterate and swap elementsNone
19Convert array to sliceUse array as a sliceUse array as a sliceNone
20Convert slice to arrayUse slicing or iterateUse slicing or iterateNone
21Compare arrays/slicesIterate and compare elementsIterate and compare elementsNone
22Initialize with zero valuesArrays are automatically zero-initializedArrays are automatically zero-initializedNone
23Multidimensional arraysvar arr [size1][size2]typevar matrix [3][3]intNone
24Compare equality of slicesIterate and compare elementsIterate and compare elementsNone
25Clear a sliceCreate a new sliceCreate a new sliceNone

Working With Strings

TipPurposeSyntaxExampleRequired Package
26Declare a stringvar str stringvar message stringNone
27Initialize a stringstr := "text"name := "Alice"None
28Concatenate stringsresult := str1 + str2greeting := "Hello, " + nameNone
29Find the lengthlen(str)length := len(str)None
30Access a characterchar := str[index]first := name[0]None
31Iterate over charactersfor index, char := range str { }for i, letter := range greeting { }None
32Convert to uppercasestrings.ToUpper(str)upper := strings.ToUpper(name)"strings"
33Convert to lowercasestrings.ToLower(str)lower := strings.ToLower(name)"strings"
34Check if a substring existsstrings.Contains(str, substr)found := strings.Contains(text, "Go")"strings"
35Count occurrences of a substringstrings.Count(str, substr)count := strings.Count(text, "is")"strings"
36Replace substringsstrings.Replace(str, old, new, n)modified := strings.Replace(text, "Go", "Golang", -1)"strings"
37Trim whitespacestrings.TrimSpace(str)trimmed := strings.TrimSpace(" Hello, Go ")"strings"
38Split into substringsstrings.Split(str, sep)parts := strings.Split(text, " ")"strings"
39Join substringsstrings.Join(slice, sep)sentence := strings.Join(parts, " ")"strings"
40Find the index of a substringstrings.Index(str, substr)index := strings.Index(text, "world")"strings"
41Check if it starts with a prefixstrings.HasPrefix(str, prefix)startsWith := strings.HasPrefix(text, "Hello")"strings"
42Check if it ends with a suffixstrings.HasSuffix(str, suffix)endsWith := strings.HasSuffix(text, "Go")"strings"
43Convert to byte slice[]byte(str)bytes := []byte("Hello, Go")None
44Convert to rune slice[]rune(str)runes := []rune("こんにちは")None
45Compare stringsstrings.Compare(str1, str2)result := strings.Compare(a, b)"strings"
46Check if two strings are equalstr1 == str2isEqual := a == bNone
47Find and replace using regexregexp.ReplaceAllString(src, replacement)result := regexp.ReplaceAllString(text, "\\w+", "X")"regexp"
48Match using regexregexp.MatchString(pattern, str)matched, _ := regexp.MatchString("G[o]+", text)"regexp"
49Extract matched substringsregexp.FindAllString(src, -1)matches := regexp.FindAllString(text, "\\w+")"regexp"
50Validate email addressesUse a regular expressionUse a regular expressionNone

Other Tricks

TipPurposeSyntaxExampleRequired Package
51Parse JSON to a structjson.Unmarshal(data, &structVar)err := json.Unmarshal([]byte(jsonData), &user)"encoding/json"
52Convert struct to JSONjson.Marshal(structVar)jsonStr, err := json.Marshal(user)"encoding/json"
53Pretty-print JSONjson.MarshalIndent(structVar, "", " ")jsonStr, err := json.MarshalIndent(user, "", " ")"encoding/json"
54Encode to Base64base64.StdEncoding.EncodeToString([]byte(data))encoded := base64.StdEncoding.EncodeToString([]byte("hello"))"encoding/base64"
55Decode from Base64base64.StdEncoding.DecodeString(encoded)decoded, err := base64.StdEncoding.DecodeString(encoded)"encoding/base64"
56Convert string to integerstrconv.Atoi(str)num, err := strconv.Atoi("42")"strconv"
57Convert integer to stringstrconv.Itoa(int)str := strconv.Itoa(42)"strconv"
58Convert string to float64strconv.ParseFloat(str, 64)value, err := strconv.ParseFloat("3.14", 64)"strconv"
59Convert float64 to stringstrconv.FormatFloat(flt, 'f', -1, 64)str := strconv.FormatFloat(3.14, 'f', -1, 64)"strconv"
60Check if a string is a numberCustom functionisNum := isNumeric("123")None
61Check if a string is a valid URLCustom functionisValid := isValidURL("https://example.com")None
62Remove non-alphanumeric charactersCustom functioncleaned := removeNonAlphaNumeric("Hello, $Go!")None
63Convert string to bytes[]byte(str)byteData := []byte("Hello")None
64Convert bytes to stringstring(byteSlice)text := string(byteData)None
65Trim specific charactersstrings.Trim(str, cutset)trimmed := strings.Trim("++Hello++", "+")"strings"
66Remove duplicates from a string sliceCustom functionunique := removeDuplicates([]string{"a", "b", "a", "c"})None
67Reverse a stringCustom functionreversed := reverseString("hello")None
68Find the longest common prefixCustom functionprefix := longestCommonPrefix([]string{"abc", "ab", "abcd"})None
69Find the shortest common suffixCustom functionsuffix := shortestCommonSuffix([]string{"abc", "bc", "abcd"})None
70Convert string to title caseCustom functiontitle := toTitleCase("hello, world")None
71Shuffle characters in a stringCustom functionshuffled := shuffleString("abcde")None
72Check if a string is palindromeCustom functionisPalin := isPalindrome("racecar")None
73Extract email addressesCustom functionemails := extractEmails("Contact us at info@example.com")None
74Remove HTML tagsCustom functionplainText := removeHTMLTags("<p>Hello, <b>world</b>!</p>")None
75Generate random stringsCustom functionrandomStr := generateRandomString(8)None