Essential Golang Knowledge for Beginners

1. Introduction

Go is a compiled high-level programming language. It means that before the code is executed, It is compiled into machine code by the Go compiler.
Go is commonly used to build server-side applications and backend services.

2. Set up Go on a local Windows machine

Step 1: Download the Go Installer

– Click on the “Download Go” button in the official Golang website: https://go.dev/doc/install
– Download the Windows installer package (.msi file)

Step 2: Run the Installer

– Open the downloaded .msi file. Follow the prompts accordingly and Golang will be installed
– Type “go version” on terminal to verify if you have Go installed on your PC or not

– Type “go env GOROOT” This command will output the installation directory of Go, which should be C:\Program Files\Go

3. First “Hello World” Program in VSCode with Go

Step 1: Install the Go Extension for VSCode

– Click on the Extensions icon in VSCode, type “Go” in the search bar, and install the top-listed Go extension.
(Throughout this Golang blog series, I will use VSCode for development.)

Step 2: Create a new directory for your project

mkdir greeting
cd greeting

Step 3: Initialize the Go module

go mod init github.com/khanh1010/greeting

After running these commands, your project directory will look like this:
A typical Go project follows a standard structure, which includes modules and packages. Here’s an overview:
Module: A module is a collection of Go packages stored in a directory with a go.mod file at its root.
The go.mod file defines the module’s path and its dependencies.
Here is the initial state of mod file:

Packages: Packages are directories inside the module that contain all Go source files.

Step 4: Create a file named hello.go and paste the following code:

package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}

Save the file. Then, open the terminal in VSCode and type “go run hello.go” to see “Hello World!” printed.

Now, let’s explore the code snippet
package main
– Every Go file starts with a package declaration. The package main statement indicates that this Go file belongs to the main package.
– Additionally, main package is special. It’s the entry point for executable programs. When you compile and run a Go program, it looks for a main package and executes the main function within it.
import “fmt”
– The import keyword is used to include packages
– In this case, fmt is a built-in package which provides functions for formatting input and output
func

func main() {
fmt.Println("Hello World!")
}

We declare a function using the syntax func main() {}
In Go, func is used to define functions, and main is a special function name indicating the entry point for executable Go programs.
Inside the main function, we use fmt.Println(“Hello World!”) to print the text “Hello World!”
Here, fmt refers to the package imported as above, and Println is a method provided by this package.

4. Variables

There are several ways to declare variables in Go
– Using the var keyword

var name string
var grade int

– Short Variable Declaration

name := “Kelly”
grade := 8

Note:
– The short variable declaration uses the := syntax and infers the type of the variable from the value on the right-hand side.
– It can only be used inside functions and cannot be used at the package level.

5. Strings

I will not go into detail about primitive data types in this blog. Please refer here for more information: https://www.geeksforgeeks.org/data-types-in-go/
This time, I will just take some notes.
In Golang, strings are defined using double quotes (“) only, not single quote.
Single quotes (‘) are used for runes, which is a data type that represents a single Unicode code point.

package main
import "fmt"
func main() {
// Declare a rune variable
var r rune
r = '日'
// Print the rune and its Unicode code point
fmt.Printf("Rune: %c\n", r)
fmt.Printf("Unicode code point: %U\n", r)
}

6. Arrays

To declare an array, you specify the type of elements it will hold and its size. For example:

var myArray [5]int

Here, the array is declared to hold 5 integers.
You can also initialize an array with specific values at the time of declaration:

myArray := [5]int{1, 2, 3, 4, 5}

In this case the array is initialized with the values 1, 2, 3, 4, and 5

7. Slice

Slice is similar to an array but offer more flexibility, particularly in their ability to dynamically resize.
To declare a slice, it is quite similar to an array but you do not specify the size in brackets []

var mySlice []int

or

mySlice := []int

You can initialize a slice with values by adding them inside curly braces:

var mySlice []int{1, 2, 3, 4, 5}

or

mySlice := []int{1, 2, 3, 4, 5}

You also can create an empty slice using make() with a specific length and capacity.
For example, to create a slice with a specific length of 2 and a capacity of 5 using make()

mySlice := make([]int, 2, 5)

This creates a slice with a length of 2, initialized with zero values, and a capacity of 5.
Even though the capacity is initially set to 5, when we append more elements to the slice, Go automatically increases its capacity if needed.
We use append() function to add more elements to the slice:

mySlice = append(mySlice, 1)
mySlice = append(mySlice, 2)

In these examples, append() adds elements 1 and 2 to mySlice
You can initialize a slice from an array:

myArray := [5]int{1,2,3,4,5}
mySlice = myArray[:]

Please remember that when we create multiple slices from the same array, modifying elements through one slice will reflect changes in the other slice because they reference the same data in memory.
For better visualization, please run the code on your end.

package main

import "fmt"

func main() {

    // Create an array with 5 numbers

    myArray := [5]int{1, 2, 3, 4, 5}

    // Create slices from the array

    mySlice1 := myArray[:]

    mySlice2 := myArray[:]

    // Modify an element in mySlice

    mySlice1[0] = 11

    // Print the first element of mySlice2

    fmt.Println(mySlice2[0]) // Prints: 11

}

7. Maps

Unlike slices or arrays, which are automatically initialized to their zero values (nil or empty), maps are not automatically initialized.
So in Go, maps do need to be initialized function before use.
To declare and initialize a map in same line:

var myMap = make(map[string]int)

or

var myMap = map[string]int{}

or

myMap := make(map[string]int)

or

myMap := map[string]int{}

To declare and initialize a map with some initial key-value pairs:

myMap := map[string]int{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5}

8. Struct

A struct is used to create a collection of members of different data types, into a single variable.
To declare a struct in Go, you define a new type with a name and specify its fields, for example:

type Student struct {

    ID        int

    FirstName string

    LastName  string

    Age       int

    Courses   []string

}

To create instances (or objects) of the above struct

student := Student {

    ID: 1,

    FirstName: "Kelly"

    LastName: "Smith",

    Age: 20,

    Courses: []string{"Math", "Physics", "Computer Science"}

}

Go supports struct embedding, allowing one struct to embed another struct’s fields:
For example:

type Address struct {

    City  string

    State string

}

type Student struct {

    ID        int

    FirstName string

    LastName  string

    Age       int

    Courses   []string

    Address   // Embedded struct Address

}

You can define methods on structs to operate on struct instances:

func (s Student) CreateFullNameStudent() string {

    return s.FirstName + " " + s.LastName

}

fmt.Println("Full Name:", student. CreateFullNameStudent())

Let's move on to the pointer

9. Pointer

Suppose you have a variable:

name := "Kelly"

Then, you declare the pointer ptr to point to the memory address of a variable name

namePtr = &name

Now, to access the value stored at the memory address, you use the dereference operator *:

nameValue = *namePtr

You can use pointers to structs for efficient memory management or when you want to modify the original struct:

var ptrToStudent *Student = &student
ptrToStudent.Age = 22 // Modify age through pointer

10. Interface

Interfaces in Go provide a way to define sets of method signatures that a type can implement.
To declare an interfaces, we use type keyword followed by the interface name and a set of method signatures, for example:

type Animal interface {

    Speak() string

    Move() string

}

For better understanding, Let’s implement the above interface.
You can run the code below from your end.

package main

import (

"fmt"

"reflect"

)

type Animal interface {

    Speak() string

    Move() string

}

type Cat struct {

    Name string

}

// Implement Speak method for Cat

func (c Cat) Speak() string {

    return c.Name + " says Meow!"

}

// Implement Move method for Cat

func (c Cat) Move() string {

    return c.Name + " is walking"

}

// Function to print details of an Animal

func PrintAnimalDetails(a Animal) {

    fmt.Println("Animal:", reflect.TypeOf(a).Name())

    fmt.Println("Sound:", a.Speak())

    fmt.Println("Movement:", a.Move())

}

func main() {

    // Create an instance of Cat

    cat := Cat{Name: "Whiskers"}

    // Print details using the interface

    PrintAnimalDetails(cat)

}

Run the code and we will get the output:

So far, so good! We’ve covered the basics of Golang. Stay tuned for more in-depth topics.

関連記事

カテゴリー:

ブログ

情シス求人

  1. チームメンバーで作字やってみた#1

ページ上部へ戻る