Go Language


What is Go (Golang)?

  • A programming language designed at Google
  • A static typing language
  • Simple syntax similar to C language
  • Memory safe, garage collection, structural typing (like a duck typing), concurrency
  • Rich standard libraries

What are applications of Golang?

  • System programming (alternatives to C/C++)
  • Backend servers

Notice

  • This lecture provides fundamental codes that are needed for TDD (Test-Driven Development) with Golang.
  • We skip the detailed syntax of Golang (Google it! or ask to ChatGPT).

Hello World

Project Initialization

Start by creating a new project directory and initializing a Go module:

mkdir hello
cd hello
go mod init hello
  • mkdir hello: Create a new directory named hello.
  • cd hello: Change into the hello directory.
  • go mod init hello: Initialize a new Go module named hello. This creates a go.mod file that defines the module’s name and its dependencies.
  • Note: Visual Studio Code opens the current directory as a workspace, so you can open the hello directory in VS Code.

Write a code for Hello World

  • Create a file hello.go
package main

import "fmt"

func main() {
    fmt.Println("Hello world")
}

  • Execute the following command in Terminal
go run hello.go
  • Output
$ go run hello.go
Hello world

Explanation

  • package main and main function are required for the entry point of program execution (same as main function of C language). The main function should be placed in main package.
  • import declares what libraries (packages) are used in the code.
    • fmt is a library for formatting and printing
  • fmt.Println indicates the function Println in the library fmt.There is no way to omit the name of library, i.e., fmt.Println cannot be written by Println.
  • go run provides an execution of code similar to a script language, but it involves both compiling and executing.
    • go build: the command for compiling

A minimum checklist: To write codes with Golang

This is a minimum checklist to learn Golang. Ask ChatGPT or Google for more details.

  • Check the fundamental types of Golang; int, float64, string
  • Check the declaration of variables; the usage of var and :=
  • Check the slice and its methods
  • Check the type definition and the structure; type
  • Check the declaration of methods for a type; methods, receiver and pointer receiver

Summary

  • Go is a programming language designed at Google, known for its simplicity and efficiency.
  • It is statically typed, memory safe, and has a rich standard library.
  • The lecture provides a basic introduction to Go, focusing on the “Hello World” program and essential concepts.
  • Students are encouraged to explore more about Go’s syntax and features through online resources or ChatGPT.