Skip to content

Latest commit

 

History

History
127 lines (91 loc) · 3.06 KB

go-101.md

File metadata and controls

127 lines (91 loc) · 3.06 KB

go 101

Below is just enough to get you going in go. For full introduction go here https://tour.golang.org

packages and package main

Packages in go are similar to Java and other languages for structuring code. Executable commands must be in the main package.

package main

func main()

Functions in go are defined with func and like Java there needs to be a main function for an executable.

func main() {
	name := "World"
	fmt.Println("Hello, " + name)
}

run above code

Variables

Variables can be declared with keywork var. They can also be inferrd through assignment using :=. A variable can be reassigned a value using =.

Variables are scoped to innermost block {} they are declared, or to package if not in an enclosing block.

Names of package variables (as well as functions, structs, interfaces, etc.) that start with upper case are public. Otherwise are accessible only to the package they are declared.

# var usage for declared type and assignment
var anotherName string
anotherName = "Earth"

# inferred type from assignement.
name := "World"

# use = to reassign
name = "world"

A struct is collection of fields (data). A struct can have behavior with functions associated to it.

type Rectangle struct {
    length, width int
}

func (r Rectangle) Area() int {
    return r.length * r.width
}

func main() {
    r1 := Rectangle{4, 3}
    fmt.Println("Rectangle is: ", r1)
    fmt.Println("Rectangle area is: ", r1.Area())
}

run the above code

loops

go only has for loops. They have an init statement, condition, and post statement like C/Java/etc.

sum := 0
for i := 0; i < 10; i++ {
    sum += i
}
fmt.Println(sum)

run the above code

range

for loops can also iterate over a range. A range can be an array/slice, map, etc. In the example below, i is the index and v is the value.

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

for i, v := range pow {
    fmt.Printf("2**%d = %d\n", i, v)
}

run the above code

arrays and slices

arrays in go are much like any other language and have a fixed size. In go you usually are are dealing with slices, which are dynamically-sized, flexible view into the elements of an array

// array
var array [5]int
// slice
var slice []int

// invalid!
// slice = array

// valid, create a slice
slice = array[:]

run the above code

More references

Next

Hello World in Go

pirate gopher