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
If your code is organized into multiple files, you can run the go file with the following command:
make a executable file
run the executable file
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
Operator | Name | Example |
---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
++ | Increment | i++ |
– | Decrement | i-- |
Assignment
Operator | Example | Same As |
---|
= | x = 5 | x + y |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
Comparison
Operator | Name | Example |
---|
== | equal to | x == y |
!= | not equal to | x != y |
> | greater than | x > y |
< | less than | x < y |
>= | greater than or equal to | x >= y |
<= | less than or equal to | x <= y |
Logical
Operator | Name | Description | Example |
---|
&& | AND | returns true if both statements are true | x < 5 && x < 10 |
|| | OR | returns true if one of the statements is true | x < 5 || x < 4 |
! | NOT | reverse 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}
|