Understanding Go Language. Duration: 19.03 mins

Comparison with Python and NodeJS

Click Play Button to Start

Concurrency Model

  • Go: Concurrency via goroutines
  • Python: Concurrency with threading
  • NodeJS: Event-driven, non-blocking I/O

Example in Python with Threading


import threading

def print_numbers():
    for i in range(1, 6):
        print(i)

# Running two threads concurrently
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

Example in Go with Goroutines


package main

import (
    "fmt"
    "sync"
)

func printNumbers(wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}

func main() {
    var wg sync.WaitGroup
    wg.Add(2)

    go printNumbers(&wg)
    go printNumbers(&wg)
    
    wg.Wait()
}

Explanation:

  • `wg.Add(2)`: Wait for two goroutines
  • `go printNumbers(&wg)`: Start each goroutine
  • `wg.Wait()`: Wait until both goroutines call `wg.Done()`
flowchart TD Start -->|Start| AddWC(("Add to WaitGroup")) -->|Start each goroutine| Go1(("Goroutine 1")) Start -->|Start| AddWC -->|Start each goroutine| Go2(("Goroutine 2")) Go1 --> Do1("Do work 1") Go2 --> Do2("Do work 2") Do1 --> Done1(("Call wg.Done()")) Do2 --> Done2(("Call wg.Done()")) Done1 --> Check1(("Check await")) Done2 --> Check2(("Check await")) Check1 -->|Both Done| Completed(("Completed")) Check2 -->|Both Done| Completed Completed -->|Continue| End style Start fill:#f9f, stroke:#333, stroke-width:2px style End fill:#f9f, stroke:#333, stroke-width:2px style AddWC fill:#f9f, stroke:#333, stroke-width:2px style Go1 fill:#f9f, stroke:#333, stroke-width:2px style Go2 fill:#f9f, stroke:#333, stroke-width:2px style Do1 fill:#f9f, stroke:#333, stroke-width:2px style Do2 fill:#f9f, stroke:#333, stroke-width:2px style Done1 fill:#f9f, stroke:#333, stroke-width:2px style Done2 fill:#f9f, stroke:#333, stroke-width:2px style Check1 fill:#f9f, stroke:#333, stroke-width:2px style Check2 fill:#f9f, stroke:#333, stroke-width:2px style Completed fill:#f9f, stroke:#333, stroke-width:2px style End fill:#f9f, stroke:#333, stroke-width:2px

Performance and Efficiency

  • Go: Statically typed, compiled, superior performance for CPU-bound tasks
  • Python: Dynamically typed, interpreted, generally slower
  • NodeJS: Fast and efficient for I/O-bound applications with V8 engine

Simplicity vs. Versatility

  • Go: Minimalistic design, straightforward syntax, eases maintenance
  • Python: Readability and conciseness, excellent for rapid development
  • NodeJS: JavaScript on client & server sides, ideal for full-stack development

Standard Library and Ecosystem

  • Go: Robust standard library for web servers and networking
  • Python: Extensive standard library ("batteries included") and large third-party ecosystem
  • NodeJS: Rich set of modules via npm registry

Tooling

  • Go: Integrated toolchain (`go build`, `go test`, `go fmt`)
  • Python and NodeJS: Comprehensive tools and third-party utilities
  • Go: Unified developer experience
flowchart TD A[Integrated toolchain] -->|Go build| B(go build) A -->|Go test| C(go test) A -->|Go fmt| D(go fmt) E[Comprehensive tools] -->|Python| F(Python) E -->|NodeJS| G(NodeJS) H[Unified developer experience] -->|Go| I(Go)

Conclusion:

  • Choice of language depends on project requirements
  • Consider concurrency, rapid development, performance, and toolset
  • Also factor in team preferences and expertise

Benefits of using Go

Click Play Button to Start

Go: The Benefits of Using Golang

  • Introduction to Golang

Simplicity and Readability

  • Emphasizes simplicity and readability
  • Reduces cognitive load on developers
  • Avoids the complexity of languages like C++
flowchart TD A(Simplicity and Readability) B(Emphasizes simplicity and readability) C(Reduces cognitive load on developers) D(Avoids the complexity of languages like C++) A --> B B --> C C --> D

Concurrency Model

  • Built-in concurrency model
  • Utilizes 'goroutines' and 'channels'
  • Simplifies development of concurrent applications
graph LR A(Built-in concurrency model) --> B(Utilizes 'goroutines' and 'channels') B --> C(Simplifies development of concurrent applications)

Fast Compilation

  • Impressive compilation speed
  • Enhances developer productivity
  • Quick feedback loop, similar to Python

Performance

  • Performance near to C and C++
  • Statically typed and compiled
  • Substantial performance compared to Node.js

Robust Standard Library

  • Comprehensive standard library
  • Support for I/O, HTTP servers, networking, encryption
  • Minimal need for third-party libraries

Cross-Platform

  • Supports cross-compilation
  • Compile programs for any platform without changing source code

Garbage Collection

  • Simple and efficient garbage collection system
  • Automatically deallocates unused memory

Great Tooling

  • User-friendly toolchain
  • Tools like 'gofmt' for formatting code
  • 'godoc' for documentation

Growing Ecosystem

  • Increasing number of frameworks, libraries, tools
  • Steady rise in ecosystem

Strong Typing

  • Avoids pitfalls of looser typing
  • Catches more errors at compile-time
  • Fewer surprises at runtime

Static Binary Compilation

  • Compiles to a single binary
  • All dependencies included in the binary
  • Simplifies deployment

Ideal for Microservices & Cloud-Native Development

  • Performance and scalability benefits
  • Favored for microservices
  • Cloud-native platforms like Kubernetes use Go
pie title Languages for Microservices & Cloud-Native Development "Go" : 100

Error Handling

  • Explicit error return values
  • Similar to Python's approach
  • Caller’s responsibility to handle errors

Summary

  • Strengths in simplicity, performance, concurrency
  • Increased developer productivity
  • Improved performance and reliability of software

Go's place in Software development

Click Play Button to Start

Go Programming Language: A Brief Overview

  • Go, also known as Golang, is designed by Google.
  • Ideal for system and network programming, cloud services.
  • Known for simplicity, efficiency, and readability.

Usage in Software Development

  • Excels where performance and concurrency are critical.
  • Popular for backend development, scalable services, cloud computing.
  • Concurrency supported by goroutines and channels.
  • More memory-efficient than threads.
graph LR A(Usage in Software Development) --> B(Excels where performance and concurrency are critical) A --> C(Popular for backend development, scalable services, cloud computing) A --> D(Concurrency supported by goroutines and channels) A --> E(More memory-efficient than threads)

Standard Library Features

  • Web servers.
  • JSON encoding/decoding.
  • Cryptographic libraries.

Enables building powerful applications with minimal third-party dependencies.

Adoption by Companies

  • Used by Google, Dropbox, Docker, etc.
  • Enables scalable, high-speed networking and infrastructure.

Key Features of Go

  • Strong typing.
  • Garbage collection.
  • Efficient compilation.

Crafts reliable, maintainable, and efficient codebases.

Performance Comparison

  • Go vs Python:
    • Python: Interpreted, focuses on readability and quick development cycles.
    • Go: Compiled, performance close to C++ or Java without sacrificing productivity.
  • Go vs Node.js:
    • Node.js: Efficient in asynchronous operations but struggles with CPU-bound tasks.
    • Go: Superior performance in CPU-bound tasks, easy-to-manage concurrency.
flowchart TD GoVsPython((Go vs Python)) Python["Python: Interpreted, focuses on readability and quick development cycles."] Go["Go: Compiled, performance close to C++ or Java without sacrificing productivity."] GoVsPython --> Python GoVsPython --> Go GoVsNodeJS((Go vs Node.js)) NodeJS["Node.js: Efficient in asynchronous operations but struggles with CPU-bound tasks."] Go2["Go: Superior performance in CPU-bound tasks, easy-to-manage concurrency."] GoVsNodeJS --> NodeJS GoVsNodeJS --> Go2

Real-World Analogy

  • Go: Freight train – optimized for heavy loads and long distances with efficient resource use.
  • Python: Car – great for quick trips and ease of use.
  • Node.js: City bus – optimized for frequent stops but not ideal for heavy loads over long distances.

Installing Go

Click Play Button to Start

Installing Go

  • Visit the official Go webpage: https://golang.org/dl/
  • Choose appropriate installer for OS (Windows, macOS, Linux)
  • Download the required version (Latest: Go 1.18)
  • Follow OS-specific instructions
flowchart TD A[Visit the official Go webpage] -->|Choose appropriate installer for OS| B(Download installer for OS) B --> C{Download the required version} C -->|Go 1.18| D[Follow OS-specific instructions]

For Windows

  • Run the downloaded .msi file
  • Follow the installation wizard (Default: C:\Go )
  • Ensure C:\Go\bin is in system's Path
  • Verify with go version in Command Prompt

For macOS

  • Open the downloaded .pkg file
  • Follow the Go Installer prompts
  • Go distribution placed at /usr/local/go
  • Verify with go version in terminal

For Linux

  • Extract archive with tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz
  • Add /usr/local/go/bin to PATH
  • Update ~/.profile or ~/.bashrc with export PATH=$PATH:/usr/local/go/bin
  • Source profile/bashrc or open new terminal session
  • Verify with go version
flowchart TD A[Extract archive with tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz] --> B(Add /usr/local/go/bin to PATH) B --> C{Update ~/.profile or ~/.bashrc with export PATH=$PATH:/usr/local/go/bin} C --> D(Source profile/bashrc or open new terminal session) D --> E(Verify with go version)

Comparison with Python Installation:

  • Download installer from official website
  • Add Python to system's PATH during installation
  • Similar straightforward process for easy setup

Setting up IDE for Go

Click Play Button to Start

Setup IDE for Go

Instructions to set up an IDE for Go language, also known as "Golang".

Choosing an IDE

  • Popular IDEs for Go:
    • Visual Studio Code (VSCode)
    • GoLand by JetBrains
    • Atom with Go plugin

Example: Visual Studio Code

  • VSCode is free, open-source, and widely used.

Steps to Set Up Go on VSCode

  1. Download and Install VSCode
  2. Install the Go Extension
    • Open Extensions view ( Ctrl+Shift+X )
    • Search for "Go" extension by the Go Team at Google
    • Click 'Install'
  3. Configure the Go Extension
    • Install analysis tools when prompted
    • Tools are for features like:
      • Code navigation
      • Auto-completion
      • Formatting
      • Linting
  4. Open or Create a Go Project
    • Open an existing project or create a new one
    • VSCode will activate Go-specific tools
  5. Adjust Settings for Your Needs
    • Access settings via File > Preferences > Settings or Ctrl+,
    • Configure Go-specific settings by searching for ‘Go’
flowchart TD A[Download and Install VSCode] -->|Download from the official website| B(Download from the official website) B --> C[Install the Go Extension] C --> D(Open Extensions view (Ctrl+Shift+X)) D --> E{Search for "Go" extension by the Go Team at Google} E --> F(Click 'Install') F --> G[Configure the Go Extension] G --> H(Install analysis tools when prompted) H --> I{Tools for features like:
Code navigation
Auto-completion
Formatting
Linting} I --> J(Open or Create a Go Project) J --> K(Open an existing project or create a new one) K --> L(VSCode will activate Go-specific tools) L --> M[Adjust Settings for Your Needs] M --> N(Access settings via File > Preferences > Settings or Ctrl+,) N --> O{Configure Go-specific settings by searching for ‘Go’}

Key Takeaways

  • VSCode setup for Go involves:
    • Installation
    • Extension addition
    • Configuration
    • Project setup
    • Settings adjustment
  • Once set up, becomes a streamlined environment for Go development
flowchart TD A[VSCode setup for Go] -->|Installation| B(Extension addition) B --> C{Configuration} C -->|Project setup| D(Settings adjustment) D -->|Once set up| E(Streamlined environment for Go development)

Understanding Go's tool chain

Click Play Button to Start

Go's Toolchain

Go's tool chain is a suite of tools designed to facilitate the development, building, testing, and management of Go code.

  • Core commands of the Go toolchain:
graph LR A[Go toolchain] B[Development] C[Building] D[Testing] E[Management] A --> B A --> C A --> D A --> E
  • go build : Compiles Go source files and dependencies.
    • When run without arguments, builds the package in the current directory.
    • Takes a package name as an argument to build that package.
flowchart TD A[go build] -->|No Arguments| B{Current Directory} A --> C(Takes package name)
  • go run : Compiles and runs Go programs.
    • Convenient for quick test runs.
    • Equivalent to running go build and then executing the compiled binary.
  • go test : Runs tests in the current package.
    • Automatically calls any function of the form func TestXxx(*testing.T) .
  • go get : Adds new dependencies to your project.
    • Downloads specified packages and installs them.
  • go mod : Module maintenance command.
    • Initiate a new module, add missing and remove unused modules, and perform module-related operations.
    • Since Go 1.11, modules are the default way of managing dependencies.
  • go install : Compiles and installs the named packages and dependencies.
    • Installs resulting binary to $GOPATH/bin or $GOBIN .
  • go doc : Shows documentation for specified package or symbol.
    • Helps in understanding the API and usage of packages.
  • go fmt : Automatically formats Go source files.
    • Maintains consistency in code formatting.
  • go vet : Examines Go source code and reports suspicious constructs.
    • Examples: variable references that may not exist.
  • go clean : Removes object files from package source directories.

Typical Use of Go Toolchain in a Project

graph TB A[Initialize Project] --> B[Write Code] B --> C{Test Code} C -->|Pass| D[Build Executable] C -->|Fail| E[Debug Code] D --> F[Run Executable] F --> G{Functionality OK?} G -->|Yes| H[Release] G -->|No| I[Update Code] I --> C H --> J((End))
  1. Create workspace and use go mod init to initialize the module and create a go.mod file.
  2. Write Go code in .go files.
  3. Run go get to add external packages.
  1. Develop code and run go run for quick testing.
  2. Regularly format code with go fmt .
  3. Run tests with go test .
  1. Run go vet to check for subtle bugs before committing code.
  2. Use go build or go install to build a release version.

Comparison to Python Tools

  • go build is analogous to python setup.py build .
  • <

Quiz

Click Play Button to Start

Question 1/3

Which characteristic of Go makes it particularly suitable for high-performance services relying on concurrent processing?

Question 2/3

Which of the following statements is correct when installing Go on Linux?

Question 3/3

Which step is necessary for setting up Go on Visual Studio Code after installing the Go extension?