Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and communicating sequential processes (CSP)-style concurrency.
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
Operators | Description |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus |
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
Punctuators/Delimiters | Description |
---|---|
( ) |
Parentheses |
{ } |
Braces (Curly Brackets) |
[ ] |
Square Brackets |
, |
Comma |
; |
Semicolon |
: |
Colon |
... |
Ellipsis |
. |
Period (Dot) |
-> |
Arrow |
<-> |
Channel Arrow |
<> |
Angle Brackets (used in type conversions) |
:= |
Short Variable Declaration |
/= |
Divide and Assign |
Operator | Description |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
% |
Modulus (Remainder) |
++ |
Increment |
-- |
Decrement |
Operator | Description |
---|---|
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
Operator | Description |
---|---|
&& |
Logical AND |
|| |
Logical OR |
! |
Logical NOT |
A | B | A && B |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
A | B | A || B |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
A | !A |
---|---|
true | false |
false | true |
Operator | Description |
---|---|
& |
Bitwise AND |
| |
Bitwise OR |
^ |
Bitwise XOR (Exclusive OR) |
<< |
Left Shift |
>> |
Right Shift |
&^ |
Bit Clear (AND NOT) |
Category | Operator | Associativity |
---|---|---|
Postfix | () [] -> . ++ - - |
Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof |
Right to left |
Multiplicative | * / % |
Left to right |
Additive | + - |
Left to right |
Shift | << >> |
Left to right |
Relational | < <= > >= |
Left to right |
Equality | == != |
Left to right |
Bitwise AND | & |
Left to right |
Bitwise XOR | ^ |
Left to right |
Bitwise OR | | |
Left to right |
Logical AND | && |
Left to right |
Logical OR | || |
Left to right |
Assignment | = += -= *= /= %= >>= <<= &= ^= |= |
Right to left |
Comma | , |
Left to right |
Data Type | Description |
---|---|
bool |
Boolean |
int |
Signed Integer |
int8 |
8-bit Signed Integer |
int16 |
16-bit Signed Integer |
int32 |
32-bit Signed Integer |
int64 |
64-bit Signed Integer |
uint |
Unsigned Integer |
uint8 |
8-bit Unsigned Integer |
uint16 |
16-bit Unsigned Integer |
uint32 |
32-bit Unsigned Integer |
uint64 |
64-bit Unsigned Integer |
float32 |
32-bit Floating-point Number |
float64 |
64-bit Floating-point Number |
complex64 |
Complex Number with 32-bit real and imaginary parts |
complex128 |
Complex Number with 64-bit real and imaginary parts |
byte |
Alias for uint8 |
rune |
Unicode Code Point (Alias for int32) |
string |
String |
map[keyType]valueType |
Map |
sliceType[]elementType |
Slice |
arrayType[length]elementType |
Array |
struct |
Struct |
chan elementType |
Channel |
interface |
Interface |
Statement | Description |
---|---|
if condition { } |
Conditional statement |
if initialization; condition { } |
Initialization and conditional statement |
if expression { } else { } |
Conditional statement with an else block |
switch expression { case value: } |
Switch statement with cases |
for initialization; condition; update { } |
For loop |
for condition { } |
For loop with a condition |
for { } |
Infinite loop |
break |
Exit loop or switch |
continue |
Start next iteration of loop |
goto label |
Jump to labeled statement |
return expression |
Return from function |
defer functionCall() |
Defer function execution until surrounding function returns |
Functions are a fundamental building block in Go:
func add(x, y int) int {
return x + y
}
func main() {
result := add(3, 4)
fmt.Println("Sum:", result)
}
Slices are a key data structure in Go for working with sequences:
mySlice := []int{1, 2, 3, 4, 5}
Maps are used to represent key-value pairs in Go:
myMap := map[string]int{"a": 1, "b": 2, "c": 3}
Structs allow you to create your own data types with named fields:
type Person struct {
Name string
Age int
}
Pointers are used to store the memory address of another variable:
var x int = 42
var pointerToX *int = &x
func add(x, y int) int {
return x + y
}
func main() {
result := add(3, 4)
fmt.Println("Sum:", result)
}
Function | Description |
---|---|
close(c) |
Closes a channel |
len(v) |
Returns the length of a string, array, slice, map, or channel |
cap(v) |
Returns the capacity of a slice or channel |
new(T) |
Allocates memory for a new value of type T and returns its address |
make(T, args) |
Creates slices, maps, and channels with specific capacities or lengths |
panic(v) |
Stops normal execution of a goroutine and begins panicking |
recover() |
Stops a panicking goroutine and returns the value passed to panic |
append(s, x...) |
Appends elements to the end of a slice |
copy(dst, src []T) int |
Copies elements from a source slice to a destination slice and returns the number of elements copied |
delete(m, key) |
Deletes an element from a map |
myList := []int{1, 2, 3, 4, 5}
// Append
myList = append(myList, 6)
// Copy
newList := make([]int, len(myList))
copy(newList, myList)
// Slice
subList := myList[1:3]
// Range
for index, value := range myList {
fmt.Println(index, value)
}
var myArray [5]int
// Length
length := len(myArray)
// Iterate
for i := 0; i < length; i++ {
fmt.Println(myArray[i])
}
myString := "Hello, Go!"
// Length
length := len(myString)
// Concatenate
newString := myString + " Welcome!"
// Iterate
for index, char := range myString {
fmt.Println(index, string(char))
}
myMap := make(map[string]int)
// Insert
myMap["one"] = 1
myMap["two"] = 2
// Retrieve
value := myMap["one"]
// Delete
delete(myMap, "two")
// Check existence
if val, exists := myMap["three"]; exists {
fmt.Println("Value exists:", val)
}
// File I/O in Go involves using the "os" and "io/ioutil" packages
import (
"os"
"io/ioutil"
)
// Read file content
content, err := ioutil.ReadFile("example.txt")
if err != nil {
fmt.Println("Error reading file:", err)
} else {
fmt.Println("File content:", string(content))
}
// Write to file
err = ioutil.WriteFile("newfile.txt", []byte("Hello, Go!"), 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
}
Go is a tool for managing Go source code.
Usage:
go "command" [arguments]
The commands are:
bug start a bug report
build compile packages and dependencies
clean remove object files and cached files
doc show documentation for package or symbol
env print Go environment information
fix update packages to use new APIs
fmt gofmt (reformat) package sources
generate generate Go files by processing source
get add dependencies to current module and install them
install compile and install packages and dependencies
list list packages or modules
mod module maintenance
work workspace maintenance
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet report likely mistakes in packages
Use go help "command" for more information about a command.
Additional help topics:
buildconstraint build constraints
buildmode build modes
c calling between Go and C
cache build and test caching
environment environment variables
filetype file types
go.mod the go.mod file
gopath GOPATH environment variable
gopath-get legacy GOPATH go get
goproxy module proxy protocol
importpath import path syntax
modules modules, module versions, and more
module-get module-aware go get
module-auth module authentication using go.sum
packages package lists and patterns
private configuration for downloading non-public code
testflag testing flags
testfunc testing functions
vcs controlling version control with GOVCS
Use "go help topic" for more information about that topic.