Go Language
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 namedhello.cd hello: Change into thehellodirectory.go mod init hello: Initialize a new Go module namedhello. This creates ago.modfile 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
hellodirectory 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 mainandmainfunction are required for the entry point of program execution (same asmainfunction of C language). Themainfunction should be placed inmainpackage.importdeclares what libraries (packages) are used in the code.fmtis a library for formatting and printing
fmt.Printlnindicates the functionPrintlnin the libraryfmt.There is no way to omit the name of library, i.e.,fmt.Printlncannot be written byPrintln.go runprovides 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
varand:= - 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.