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 | fmt |
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 | var name string |
or:
1 | var ( |
Initiate a variale
Format:
1 | var name type = value |
examples:
1 | var name string = "Q1mi" |
or:
1 | var name = "Q1mi" |
and also we can use := operator to initiate a variable inside a function:
1 | package main |
If we want to ignore a value, we can use the anonymous variable with _ :
1 | func foo() (int, string) { |
Constant
Using keyword const to define a constant:
1 | const pi = 3.14 |
iota
1 | const ( |
1 | const ( |
1 | const ( |
1 | const ( |
1 | const ( |