0%

Go-Basic-Knowledge-0x01

Go - Basic Syntax

Tokens in Go

A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −

1
fmt.Println("Hello, World!")

The individual tokens are −

1
2
3
4
5
6
fmt
.
Println
(
"Hello, World!"
)

Identifiers

An identifier in go can only start with characters or _, and it is a combination of characters, numbers and underscores. For example, abc, _, _123, a123.

Keywords

There are 25 keywords in go:

1 2 3 4 5
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

And there are 37 reserved words in go:

Constants: true false iota nil

Types: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune string error

Functions: make len cap new append copy close delete complex real imag panic recover

Variable

Format of declare a variable:

1
var variable_name variable_type

examples:

1
2
3
var name string
var age int
var isOk bool

or:

1
2
3
4
5
6
var (
a string
b int
c bool
d float32
)

Initiate a variale

Format:

1
var name type = value

examples:

1
2
3
4
var name string = "Q1mi"
var age int = 18

var name, age = "Q1mi", 18

or:

1
2
var name = "Q1mi"
var age = 18

and also we can use := operator to initiate a variable inside a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"fmt"
)
// declare global variable m
var m = 100

func main() {
n := 10
m := 200 // declare local variable m
fmt.Println(m, n)
}

If we want to ignore a value, we can use the anonymous variable with _ :

1
2
3
4
5
6
7
8
9
func foo() (int, string) {
return 10, "Q1mi"
}
func main() {
x, _ := foo()
_, y := foo()
fmt.Println("x=", x)
fmt.Println("y=", y)
}

Constant

Using keyword const to define a constant:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const pi = 3.14
const e = 2.7182

const (
pi = 3.14
e = 2.718
)

// n1 = n2 = n3 = 100
const (
n1 = 100
n2
n3
)

iota

1
2
3
4
5
6
const (
n1 = iota //0
n2 //1
n3 //2
n4 //3
)
1
2
3
4
5
6
const (
n1 = iota //0
n2 //1
_
n4 //3
)
1
2
3
4
5
6
7
const (
n1 = iota //0
n2 = 100 //100
n3 = iota //2
n4 //3
)
const n5 = iota //0
1
2
3
4
5
6
7
8
const (
_ = iota
KB = 1 << (10 * iota)
MB = 1 << (10 * iota)
GB = 1 << (10 * iota)
TB = 1 << (10 * iota)
PB = 1 << (10 * iota)
)
1
2
3
4
5
const (
a, b = iota + 1, iota + 2 //1,2
c, d //2,3
e, f //3,4
)