Below is just enough to get you going in go. For full introduction go here https://tour.golang.org
Packages in go are similar to Java and other languages for structuring code.
Executable commands must be in the main
package.
package 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)
}
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())
}
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)
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)
}
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[:]
- https://golang.org/doc/effective_go.html be more effective at writing Go
- https://golang.org/doc/code.html to learn how to organize your Go workspace
- https://golang.org/ref/spec learn more about the language itself
- https://golang.org/doc/#articles a lot more reading material
- https://golang.org/doc/editors.html editor plugins for go
- https://www.jetbrains.com/go/ Goland IDE from JetBrains