[Go](EN) Go language beginner basic usage

Summarize about basice usage of Go.

This post assumes that reader already know about other computer languages. This is not for computer language beginner.


Environment and Prerequisite

  • Go(1.15.8)
  • Experience with other programming languages


Installation

Mac

$ go version
go version go1.15.8 darwin/amd64

Ubuntu

  • Download file
curl https://golang.org/dl/go1.15.8.linux-amd64.tar.gz -o go1.15.8.linux-amd64.tar.gz
  • Install file
sudo tar -C /usr/local -xzf go1.15.8.linux-amd64.tar.gz
  • Add /usr/local/go/bin to PATH environment variable
  • It it fine to use like below but I recommend add to ~/.bash_profile or ~/.bashrc.
export PATH=$PATH:/usr/local/go/bin


Build and Test

  • Skip project directory structure because this only for basic language usage.

Write Basic Code

test.go

package main

import "fmt"

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

Build and Run

  • Run after build
$ go build test.go
$ ./test
Hello, world!
  • Also possible like below
$ go run test.go
Hello, world!


Usage

Basic Code Form

test.go

// package name
// every Go program is made up of packages
// programs start running in package main
package main

// import other packages
import "fmt"

// main function
// it is like "void main()" in C language
func main() {
	fmt.Println("Hello, world!")
}
Hello, world!


Variable Declaration

Characteristics

  • Declare var variable type(its form is different from others)
  • There is pointer.
  • It can be declared in various ways like below.
package main

import "fmt"

func main() {
	/*
	variable examples
	*/
	var i int
	i = 1

	var j = 2

	var a,b int
	a = 3
	b = 4

	x := 5

	fmt.Println(i, j, a, b, x)


	/*
	constant examples
	*/

	const c = 10
	const str = "string"

	// multiple constants
	const (
    	visa = "Visa"
    	master = "MasterCard"
    	amex = "American Express"
	)

	fmt.Println(c, str, visa, master, amex)


	/*
	pointer example
	*/

	var ptrVal int = 100
	var ptr *int = &ptrVal

	*ptr = 150

	fmt.Println(ptrVal, *ptr)
}
1 2 3 4 5
10 string Visa MasterCard American Express
150 150


Condition Statement - if

Characteristics

  • After if must be true or false not a number.
package main

import "fmt"

func main() {
    testVal := 10

    if testVal % 3 == 1 {
        fmt.Println("Remainder is 1")
    } else if testVal % 3 == 2 {
        fmt.Println("Remainder is 2")
    } else {
        fmt.Println("Remainder is 0")
    }
}
Remainder is 1


Condition Statement - switch

Characteristics

  • It breaks switch statement if one case statement is settled.
  • If use fallthrough, then it continues next case statement.
package main

import "fmt"

func main() {
	var name string
    var category = 2

    switch category {
    case 1:
        name = "Good"
    case 2:
        name = "Very Good"
    case 3, 4: // multiple value can be used in case
        name = "Super Nice"
    default:
        name = "Power"
    }
    fmt.Println(name)
}
Very Good


Iteration - for

Characteristics

  • There is no while statement and only for statement is exist. We can use for statement like while statement.
  • Also we can use continue and break like C language.
package main

import "fmt"

func main() {

	// basic form
	var sum int = 0

	for i := 1; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)


	// range usage with array
	names := []string {"김씨", "이씨", "박씨"}

	// index variable is index of array or slice
	for index, name := range names{
		fmt.Println(index, name)
	}


	// for statement with only condition
	sum = 0
	i := 0

	for i < 10 {
		sum += i
		i++
	}
	fmt.Println(sum)
}
45
0 김씨
1 이씨
2 박씨
45


Function

Characteristics

  • It can return multi values like python.
  • ‘Pass By Reference’ exists like C++.
package main

import "fmt"

func exampleFunc (msg string) {
	fmt.Println(msg)
}

func exampleFuncReturn (msg string) string{
	return msg
}

func exampleFuncReturnMultiple (first int, second int) (int, int){
	return first, second
}

func exampleFuncPassByReference (val *int){
	*val += 10
}

func main() {
	exampleFunc("exampleFunc test")

	fmt.Println(exampleFuncReturn("exampleFuncReturn test"))

	a,b := exampleFuncReturnMultiple(3, 4)
	fmt.Println(a, b)

	var testVal int = 100
	exampleFuncPassByReference(&testVal)
	fmt.Println(testVal)
}
exampleFunc test
exampleFuncReturn test
3 4
110


Anonymous Function

Characteristics

  • We can assign function to variable and also there anonymous function which does not have function name.
package main

import "fmt"

func main() {

    sum := func (values []int) int {
        res := 0
        for _, val := range values {
            res += val
        }
        return res
    }

    fmt.Println(sum([]int {1, 2, 3}))


    sum2 := func (values ... int) int {
        res := 0
        for _, val := range values {
            res += val
        }
        return res
    }

    fmt.Println(sum2(1, 2, 3))
}
6
6


Array

package main

import "fmt"

func printResult(values [3]int) {

    for _, val := range values{
        fmt.Println(val)
    }
    fmt.Println()
}

func main() {

    var arr1 [3]int
    arr1[0] = 1
    arr1[1] = 2
    // arr1[2] will be 0 it is default value

    var arr2 = [3] int {1, 2, 3}
    var arr3 = [...] int {1, 2, 3}

    printResult(arr1)
    printResult(arr2)
    printResult(arr3)
}
1
2
0

1
2
3

1
2
3

Slice

Characteristics

  • It is dynamic size array. It supports append, merge, copy and sub-slice.
package main

import "fmt"

func main() {

    var sliceExample []int   
    sliceExample = []int{1, 1, 1}
    // also same as below
    // sliceExample := make([]int, 3, 1)


    // append
    sliceExample = append(sliceExample, 2)
    sliceExample = append(sliceExample, 3, 4, 5)
    fmt.Println(sliceExample)
    fmt.Println()


    // append slices
    sliceExampleA := []int{1, 2, 3}
    sliceExampleB := []int{4, 5, 6}
    fmt.Println(append(sliceExampleA, sliceExampleB...))
    fmt.Println()


    // sub-slice
    sliceExample  = []int{1, 2, 3, 4, 5}
    fmt.Println(sliceExample[:]) // 1 2 3 4 5
    fmt.Println(sliceExample[2:]) // 3 4 5
    fmt.Println(sliceExample[:4]) // 1 2 3 4
    fmt.Println(sliceExample[2:4]) // 3 4
}
[1 1 1 2 3 4 5]

[1 2 3 4 5 6]

[1 2 3 4 5]
[3 4 5]
[1 2 3 4]
[3 4]


Map

Characteristics

  • There is no order in map iteration.
package main

import (
    "fmt"
    "strconv"
)

func main() {

    var exampleMap map[string]int
    exampleMap = make(map[string]int)

    // add
    exampleMap["Mike"] = 100
    exampleMap["John"] = 110
    exampleMap["Jennie"] = 120

    // delete
    delete(exampleMap, "John")

    fmt.Println(exampleMap["Mike"])
    fmt.Println()

    // map iteration
    for key, value := range exampleMap {
        fmt.Println(key, value)
    }
    fmt.Println()

    // check key exist
    val, exist := exampleMap["Jennie"]
    if exist {
        fmt.Println("exist! its value is " + strconv.Itoa(val))
    }

}
100

Mike 100
Jennie 120

exist! its value is 120


Reference