Sage-Code Laboratory
index<--

Go Syntax

Go syntax is derived from C. It is a curly braced language. The symbols, operators and punctuation are similar to C. Go is using static types with type inference. That means we can create variables without declaring an explicit type.

Example: "hello world" program.

package main

//import the format package
import "fmt"

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

Try it: go.dev/play

Statements

Variables

The var statement declares a list of variables. In variable declaration the type name is specified last. This is good since the type is optional. A var statement can be at package or function level. So we can have global variables and local variables.

Example.

//variables.go
package main

import "fmt"

var i, j int = 1, 2

func main() {
    var (
        c = true;
        p = false; 
        g = "no";
    )
	fmt.Println(i, j, c, p, g)
}

Try it: go.dev/play

Initial value

A var declaration can include one initializer for each variable. Initializer is usually a constant literal. If an initializer is present, the type can be omitted. The variable will take the type of the initializer. Read the example below to understand better this concept:

//file var_list.go
package main

import "fmt"

var i, j int = 1, 2

func main() {
    var c , p, g = true, false, "no"
	fmt.Println(i, j, c, p, g)
}

Constants

In Go it is good to use constants instead of regular variables to define numbers or other values that will not change during program execution.

//file pub_con.go
package main

import "fmt"

const Pi = 3.14

func main() {
	const World = "世界"
	fmt.Println("Hello", World)
	fmt.Println("Happy", Pi, "Day")

	const Truth = true
	fmt.Println("Go rules?", Truth)
}

Try it: go.dev/play

Numeric Constants

Numeric constants are high-precision values. An untyped constant takes the type needed by its context using type inference.

//file huge_con.go
package main

import "fmt"

const (
	// Create a huge number by shifting a 1 bit left 100 places.
	// In other words, the binary number that is 1 followed by 100 zeroes.
	Big = 1 << 100
	// Shift it right again 99 places, so we end up with 1<<1, or 2. 
    Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
	return x * 0.1
}

func main() {
	fmt.Println(needInt(Small))
	fmt.Println(needFloat(Small))
	fmt.Println(needFloat(Big))
}

Try it: go.dev/play

Keywords

The following keywords are reserved and may not be used as identifiers.

Keyword Description
package A package is a collection of related Go files.
import Imports a package or type into the current package.
func Declares a function.
var Declares a variable.
const Declares a constant.
for Loops over a range of values.
if Executes a block of code if a condition is true.
while Loops over a range of values as long as a condition is true.
switch Executes a block of code based on the value of an expression.
break Exits a loop or switch statement.
continue Continues to the next iteration of a loop or switch statement.
return Returns from a function.

Operators

In the following table we show all operators used in Go. Operators are similar to functions. There are binary operators that need left and right operands and there are unary operators that need only one operand: left or right.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
<< Left shift
>> Right shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Conditional operator
! Logical NOT
%> Assignment operator
++ Increment operator
-- Decrement operator
. Dot operator
-> Indirect member access operator
[] Index operator
{{}} Slice operator

Examples:

Operators are used to create expressions and statements. Here are some examples. We will study operators in details for every data type.

Operator Description Example
Arithmetic operators Add, subtract, multiply, divide a := 1 + 2
Assignment operators Assign a value to a variable a := 3
Logical operators And, or, not if a && b { ... }
Bitwise operators Perform operations on bits a := 1 << 2
Range operators Get a range of values for i := range []int{1, 2, 3} { ... }

Read more:

Packages

Every Go program is made up of packages. Programs start running in package "main". The main package also contains the function main(). Using the import statement one package can be used into another package. By convention, the package name is the same as the last element of the import path.

//file imp_pack.go
package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println("My favorite number is", rand.Intn(10))
}

In this instance, th package "math/rand" comprises files that begin with the statement "package rand".

Import

This code groups the imports into a parenthesis, "factored" import statement.

You can also write multiple import statements, like:

import "fmt"
import "math"

But it is good style to use the factored import statement.

Public elements

In Go, a name is exported automaticly if it begins with a capital letter. This is disruptive convention that makes Go different than Java. Where in Java class names start with capital letter, but Go do not have classes.

For example the "println()" function is using capital P so is fmt.Println() instead of fmt.println(). When the package "fmt" is imported only the capital letter functions and elements are accessible using dot notation.

Note: This convention is a bit strange but you get use to it.


Read next: Data Types