0% found this document useful (0 votes)
208 views3 pages

Golang Syntax and Functions Cheat Sheet

This document provides a cheat sheet summary of Golang syntax, operators, functions, declarations, arrays, slices, and ranges. It covers basic Golang concepts like packages, imports, functions, variables, types, and control flow in 3 sentences or less.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
208 views3 pages

Golang Syntax and Functions Cheat Sheet

This document provides a cheat sheet summary of Golang syntax, operators, functions, declarations, arrays, slices, and ranges. It covers basic Golang concepts like packages, imports, functions, variables, types, and control flow in 3 sentences or less.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Golang Cheat Sheet

by [deleted] via cheatography.com/23330/cs/5127/

Basic Syntax Operators (cont) Functions (cont)

package main <= less than or equal return


import "fmt" > greater than }
func main() { >= greater than or equal var x, str = returnMulti2()
fmt.Println("Hello Go") Logical Functions As Values And Closures
} && logical and func main() {
|| logical or // assign a function to a name
Packages ! logical not add := func(a, b int) int {
Other return a + b
- package declaration at top of every source file
- executables are in package main & address of / create pointer }

- convention: package name == last name of * dereference pointer // use the name to call the
import path (import path math/rand => package <- send / receive operator function
rand) fmt.Println(add(3, 4))
- upper case identifier: exported (visible from
Functions }
other packages)
// Closures, lexically scoped:
- Lower case identifier: private (not visible from // a simple function
Functions can access values that
other packages) func functionName() {}
were
// function with parameters
Operators func functionName(param1 string,
// in scope when defining the
function
Arithmetic param2 int) {}
func scope() func() int{
+ addition // multiple parameters of the same
outer_var := 2
- subtraction type
foo := func() int { return
* multiplication func functionName(param1, param2
outer_var}
/ quotient int) {}
return foo
% remainder // return type declaration
}
& bitwise and func functionName() int {
func another_scope() func() int{
| bitwise or return 42
// won't compile because
^ bitwise xor }
outer_var and foo not defined in
&^ bit clear (and not) // return multiple
this scope
<< left shift func returnMulti() (int, string) {
outer_var = 444
>> right shift return 42, "foobar"
return foo
Comparison }
}
== equal var x, str = returnMulti()
// Closures: don't mutate outer
!= not equal // Return multiple named results
vars, instead redefine them!
< less than simply by return
func outer() (func() int, int) {
func returnMulti2() (n int, s
outer_var := 2
string) {
inner := func() int {
n = 42
s = "foobar"
// n and s will be returned

By [deleted] Published 7th September, 2015. Sponsored by CrosswordCheats.com


cheatography.com/deleted- Last updated 7th September, 2015. Learn to solve cryptic crosswords!
23330/ Page 1 of 3. http://crosswordcheats.com
Golang Cheat Sheet
by [deleted] via cheatography.com/23330/cs/5127/

Functions (cont) Declarations Arrays, Slices, Ranges (cont)

outer_var += 99 // attempt var foo int // declaration without var a = []int {1, 2, 3, 4} //
to mutate outer_var from outer initial. declare and initialize a slice
scope var foo int = 42 // declaration (backed by the array given
return outer_var // => 101 with initial implicitly)
(but outer_var is a newly redefined var foo, bar int = 42, 1302 // a := []int{1, 2, 3, 4} // shorthand
// declare and init chars := []string{0:"a", 2:"c", 1:
variable visible only inside inner) var foo = 42 // type omitted, will "b"} // ["a", "b", "c"]
} be inferred var b = a[lo:hi] // creates a
return inner, outer_var // => foo := 42 // shorthand slice (view of the array) from
101, 2 (outer_var is still 2, not const constant = "This is a index lo to hi-1
mutated by foo!) constant" var b = a[1:4] // slice from index
} 1 to 3
Variadic Functions Type Conversions var b = a[:3] // missing low index
func main() { implies 0
var i int = 42
fmt.Println(adder(1, 2, 3)) // var b = a[3:] // missing high
var f float64 = float64(i)
6 index implies len(a)
var u uint = uint(f)
fmt.Println(adder(9, 9)) // 18 // create a slice with make
// alternative syntax
nums := []int{10, 20, 30} a = make([]byte, 5, 5) // first arg
i := 42
fmt.Println(adder(nums...)) // length, second capacity
f := float64(i)
60 a = make([]byte, 5) // capacity is
u := uint(f)
} optional
// By using ... before the type // create a slice from an array
Arrays, Slices, Ranges
name of the last parameter you can x := [3]string{"", "",
Arrays
indicate that it takes zero or more ""}
var a [10]int
of those parameters. s := x[:] // a slice referencing
// declare an int array with length
// The function is invoked like any the storage of x
10. Array length is part of the
other function except we can pass
type!
as many arguments as we want. Built-in Types
a[3] = 42 // set elements
func adder(args ...int) int {
bool
i := a[3] // read elements
total := 0
string
// declare and initialize
for _, v := range args { //
int int8 int16 int32 int64
var a = [2]int{1, 2}
Iterates over the arguments
uint uint8 uint16 uint32 uint64
a := [2]int{1, 2} //shorthand
whatever the number.
uintptr
a := [...]int{1, 2} // elipsis ->
total += v
byte // alias for uint8
Compiler figures out array length
}
rune // alias for int32 ~= a
Slices
return total
character (Unicode code point) -
var a []int // declare a slice -
}
very Viking
similar to an array, but length is
float32 float64
unspecified
complex64 complex128

By [deleted] Published 7th September, 2015. Sponsored by CrosswordCheats.com


cheatography.com/deleted- Last updated 7th September, 2015. Learn to solve cryptic crosswords!
23330/ Page 2 of 3. http://crosswordcheats.com
Golang Cheat Sheet
by [deleted] via cheatography.com/23330/cs/5127/

Control structures Control structures (cont)

If switch operatingSystem {
func main() { case "darwin":
// Basic one fmt.Println("Mac OS
if x > 0 { Hipster")
return x // cases break
} else { automatically
return -x case "linux":
} fmt.Println("Linux Geek")
// You can put one statement default:
before the condition // Windows, BSD, ...
if a := b + c; a < 42 { fmt.Println("Other")
return a }
} else { // as with for and if, you can
return a - 42 have an assignment statement before
} the switch value
// Type assertion inside if switch os := runtime.GOOS; os {
var val interface{} case "darwin": ...
val = "foo" }
if str, ok := val.(string); ok
{
fmt.Println(str)
}
}
Loops
// There only for, no while, no
until
for i := 1; i < 10; i++ {
}
for ; i < 10; { // while -
loop
}
for i < 10 { // omit semicolons
}
for { //omit the condition ~
while (true)
}
Switch

By [deleted] Published 7th September, 2015. Sponsored by CrosswordCheats.com


cheatography.com/deleted- Last updated 7th September, 2015. Learn to solve cryptic crosswords!
23330/ Page 3 of 3. http://crosswordcheats.com

You might also like