Home Go
Post
Cancel

Go

1
go mod init projectname
1
2
3
4
5
6
package main
import ("fmt")

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

run the go file

1
go run filename.go

If your code is organized into multiple files, you can run the go file with the following command:

1
go run *.go

make a executable file

1
go build filename.go

run the executable file

1
./filename

Variables

1
2
3
4
5
var student1 string = "John" //type is string
var student2 = "Jane"        //type is inferred
x := 2                       //type is inferred
const PI = 3.14              //constant
const A int = 1             //constant

Declaring multiple variables

1
2
3
var a, b, c, d int = 1, 3, 5, 7
var a, b = 6, "Hello"
c, d := 7, "World!"

Operators

Arithmetic

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
++Incrementi++
Decrementi--

Assignment

OperatorExampleSame As
=x = 5x + y
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5

Comparison

OperatorNameExample
==equal tox == y
!=not equal tox != y
>greater thanx > y
<less thanx < y
>=greater than or equal tox >= y
<=less than or equal tox <= y

Logical

OperatorNameDescriptionExample
&&ANDreturns true if both statements are truex < 5 && x < 10
||ORreturns true if one of the statements is truex < 5 || x < 4
!NOTreverse the result, returns false if the result is true!(x < 5 && x < 10)

Lists

Arrays

The size of an array is fixed

1
2
3
4
5
6
7
8
9
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}
var arr3 = [...]int{1,2,3} //length is inferred


arr1[0] = 10 //change value at index 0
fmt.Println(arr1) //output: [10 2 3]

len(arr1)) //length of array (3)

Slices

The size of a slice is dynamic

1
2
var myslice1 = []int{}
var slice2 = []int{1,2,3}
This post is licensed under CC BY 4.0 by the author.