Learning Go 1 - Variables Declaration

·

2 min read

Now I finished installing Go, so time to get started!

Declare Variable

Unlike Javascript, Go is a strong type language. (Like TS) If you are from JS like me, please make sure you have basic knowledge about the type.

To declare a variable, always start with the word "var" and put the type at the end.

var year int

Also, please remember the rules below when you name your variables.

  1. Do not put "numbers" as first letter of variable
1year
  1. Do not use symbols in variable.
!year
year!2
  1. Do not use key words like "var" or "int".

Syntax

package main

import (
    "fmt"
    "path"
)

func main() {
    var file string

    _, file = path.Split("css/main.css")

    fmt.Println("file:", file)
}

Remember to always put package main in the very beginning. Then import the libraries that you need, so that we can use the methods in those libraries in our code.

Code always starts with the main function.

Inside the main function, see this line. "_, file := path.Split("css/main.css")"

What do they mean?

Since Go is a strong type language, if you declare the variable and never use it, go will complain. So, if it is a variable that you will not use, you just simply put "_". Go will know and will not complain.

Short Declaration

Different from other language, there is short declaration in Go, which makes variable declaration simpler.

For short declaration, we don't need to write type and can declare multiple variables together.

height, width, shape := 20, 20, "square"

Let's look the the same main function and change it to short declaration. Now, only 2 lines of code.

func main() {
    _, file = path.Split("css/main.css")

    fmt.Println("file:", file)
}

When to use normal declaration?

  1. If you don't know the initial value
  2. When you need package scope variable
  3. Group variables together

Apart from the situations above, we use short declaration and note that short declaration is preferred in Go.