2013-09-09 08:52:47 +04:00
|
|
|
---
|
2013-08-13 21:52:13 +04:00
|
|
|
name: Go
|
|
|
|
category: language
|
|
|
|
language: Go
|
|
|
|
filename: learngo.go
|
|
|
|
contributors:
|
|
|
|
- ["Sonia Keys", "https://github.com/soniakeys"]
|
2014-01-25 01:30:11 +04:00
|
|
|
- ["Christopher Bess", "https://github.com/cbess"]
|
2014-01-31 03:47:55 +04:00
|
|
|
- ["Jesse Johnson", "https://github.com/holocronweaver"]
|
2014-02-03 00:11:15 +04:00
|
|
|
- ["Quint Guvernator", "https://github.com/qguv"]
|
2014-05-12 00:33:08 +04:00
|
|
|
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
2013-08-13 21:52:13 +04:00
|
|
|
---
|
|
|
|
|
|
|
|
Go was created out of the need to get work done. It's not the latest trend
|
|
|
|
in computer science, but it is the newest fastest way to solve real-world
|
|
|
|
problems.
|
|
|
|
|
|
|
|
It has familiar concepts of imperative languages with static typing.
|
|
|
|
It's fast to compile and fast to execute, it adds easy-to-understand
|
|
|
|
concurrency to leverage today's multi-core CPUs, and has features to
|
|
|
|
help with large-scale programming.
|
|
|
|
|
|
|
|
Go comes with a great standard library and an enthusiastic community.
|
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
```go
|
2013-08-13 21:52:13 +04:00
|
|
|
// Single line comment
|
|
|
|
/* Multi-
|
|
|
|
line comment */
|
|
|
|
|
|
|
|
// A package clause starts every source file.
|
|
|
|
// Main is a special name declaring an executable rather than a library.
|
|
|
|
package main
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Import declaration declares library packages referenced in this file.
|
2013-08-13 21:52:13 +04:00
|
|
|
import (
|
2014-01-31 03:47:55 +04:00
|
|
|
"fmt" // A package in the Go standard library.
|
2013-08-14 06:59:19 +04:00
|
|
|
"net/http" // Yes, a web server!
|
2014-01-31 03:47:55 +04:00
|
|
|
"strconv" // String conversions.
|
|
|
|
m "math" // Math library with local alias m.
|
2013-08-13 21:52:13 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
// A function definition. Main is special. It is the entry point for the
|
|
|
|
// executable program. Love it or hate it, Go uses brace brackets.
|
|
|
|
func main() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// Println outputs a line to stdout.
|
|
|
|
// Qualify it with the package name, fmt.
|
|
|
|
fmt.Println("Hello world!")
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Call another function within this package.
|
|
|
|
beyondHello()
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Functions have parameters in parentheses.
|
2013-09-04 11:37:26 +04:00
|
|
|
// If there are no parameters, empty parentheses are still required.
|
2013-08-13 21:52:13 +04:00
|
|
|
func beyondHello() {
|
2013-08-14 06:59:19 +04:00
|
|
|
var x int // Variable declaration. Variables must be declared before use.
|
|
|
|
x = 3 // Variable assignment.
|
|
|
|
// "Short" declarations use := to infer the type, declare, and assign.
|
|
|
|
y := 4
|
2014-01-31 03:47:55 +04:00
|
|
|
sum, prod := learnMultiple(x, y) // Function returns two values.
|
|
|
|
fmt.Println("sum:", sum, "prod:", prod) // Simple output.
|
2013-08-14 06:59:19 +04:00
|
|
|
learnTypes() // < y minutes, learn more!
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Functions can have parameters and (multiple!) return values.
|
|
|
|
func learnMultiple(x, y int) (sum, prod int) {
|
2014-01-31 03:47:55 +04:00
|
|
|
return x + y, x * y // Return two values.
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Some built-in types and literals.
|
|
|
|
func learnTypes() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// Short declaration usually gives you what you want.
|
2014-01-31 03:47:55 +04:00
|
|
|
s := "Learn Go!" // string type.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
s2 := `A "raw" string literal
|
2014-01-31 03:47:55 +04:00
|
|
|
can include line breaks.` // Same string type.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
// Non-ASCII literal. Go source is UTF-8.
|
|
|
|
g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
|
|
|
|
c := 3 + 4i // complex128, represented internally with two float64's.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Var syntax with an initializers.
|
2014-01-31 03:47:55 +04:00
|
|
|
var u uint = 7 // Unsigned, but implementation dependent size as with int.
|
2013-08-14 06:59:19 +04:00
|
|
|
var pi float32 = 22. / 7
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Conversion syntax with a short declaration.
|
2014-01-31 03:47:55 +04:00
|
|
|
n := byte('\n') // byte is an alias for uint8.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Arrays have size fixed at compile time.
|
2014-01-31 03:47:55 +04:00
|
|
|
var a4 [4]int // An array of 4 ints, initialized to all 0.
|
|
|
|
a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Slices have dynamic size. Arrays and slices each have advantages
|
|
|
|
// but use cases for slices are much more common.
|
2014-01-31 03:47:55 +04:00
|
|
|
s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here.
|
|
|
|
s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0.
|
|
|
|
var d2 [][]float64 // Declaration only, nothing allocated here.
|
|
|
|
bs := []byte("a slice") // Type conversion syntax.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
p, q := learnMemory() // Declares p, q to be type pointer to int.
|
2013-08-14 06:59:19 +04:00
|
|
|
fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Maps are a dynamically growable associative array type, like the
|
|
|
|
// hash or dictionary types of some other languages.
|
|
|
|
m := map[string]int{"three": 3, "four": 4}
|
|
|
|
m["one"] = 1
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2013-08-14 06:59:19 +04:00
|
|
|
// Unused variables are an error in Go.
|
|
|
|
// The underbar lets you "use" a variable but discard its value.
|
|
|
|
_, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
|
|
|
|
// Output of course counts as using a variable.
|
|
|
|
fmt.Println(s, c, a4, s3, d2, m)
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
learnFlowControl() // Back in the flow.
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
|
|
|
|
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
|
|
|
|
func learnMemory() (p, q *int) {
|
2013-08-14 06:59:19 +04:00
|
|
|
// Named return values p and q have type pointer to int.
|
2014-01-31 03:47:55 +04:00
|
|
|
p = new(int) // Built-in function new allocates memory.
|
2013-08-14 06:59:19 +04:00
|
|
|
// The allocated int is initialized to 0, p is no longer nil.
|
2014-01-31 03:47:55 +04:00
|
|
|
s := make([]int, 20) // Allocate 20 ints as a single block of memory.
|
|
|
|
s[3] = 7 // Assign one of them.
|
|
|
|
r := -2 // Declare another local variable.
|
2013-08-14 06:59:19 +04:00
|
|
|
return &s[3], &r // & takes the address of an object.
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
func expensiveComputation() float64 {
|
|
|
|
return m.Exp(10)
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func learnFlowControl() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// If statements require brace brackets, and do not require parens.
|
|
|
|
if true {
|
|
|
|
fmt.Println("told ya")
|
|
|
|
}
|
|
|
|
// Formatting is standardized by the command line command "go fmt."
|
|
|
|
if false {
|
2014-01-31 03:47:55 +04:00
|
|
|
// Pout.
|
2013-08-14 06:59:19 +04:00
|
|
|
} else {
|
2014-01-31 03:47:55 +04:00
|
|
|
// Gloat.
|
2013-08-14 06:59:19 +04:00
|
|
|
}
|
|
|
|
// Use switch in preference to chained if statements.
|
2014-01-31 03:47:55 +04:00
|
|
|
x := 42.0
|
2013-08-14 06:59:19 +04:00
|
|
|
switch x {
|
|
|
|
case 0:
|
|
|
|
case 1:
|
2014-01-31 03:47:55 +04:00
|
|
|
case 42:
|
|
|
|
// Cases don't "fall through".
|
|
|
|
case 43:
|
|
|
|
// Unreached.
|
2013-08-14 06:59:19 +04:00
|
|
|
}
|
|
|
|
// Like if, for doesn't use parens either.
|
2014-01-31 03:47:55 +04:00
|
|
|
// Variables declared in for and if are local to their scope.
|
|
|
|
for x := 0; x < 3; x++ { // ++ is a statement.
|
2013-08-14 06:59:19 +04:00
|
|
|
fmt.Println("iteration", x)
|
|
|
|
}
|
2014-01-31 03:47:55 +04:00
|
|
|
// x == 42 here.
|
2013-08-14 06:59:19 +04:00
|
|
|
|
|
|
|
// For is the only loop statement in Go, but it has alternate forms.
|
2014-01-31 03:47:55 +04:00
|
|
|
for { // Infinite loop.
|
|
|
|
break // Just kidding.
|
|
|
|
continue // Unreached.
|
2013-08-14 06:59:19 +04:00
|
|
|
}
|
|
|
|
// As with for, := in an if statement means to declare and assign y first,
|
|
|
|
// then test y > x.
|
|
|
|
if y := expensiveComputation(); y > x {
|
|
|
|
x = y
|
|
|
|
}
|
|
|
|
// Function literals are closures.
|
|
|
|
xBig := func() bool {
|
2014-04-16 18:06:58 +04:00
|
|
|
return x > 10000 // References x declared above switch statement.
|
2013-08-14 06:59:19 +04:00
|
|
|
}
|
2014-04-16 18:06:58 +04:00
|
|
|
fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x).
|
|
|
|
x = 1.3e3 // This makes x == 1300
|
2014-01-31 03:47:55 +04:00
|
|
|
fmt.Println("xBig:", xBig()) // false now.
|
2013-08-14 06:59:19 +04:00
|
|
|
|
|
|
|
// When you need it, you'll love it.
|
|
|
|
goto love
|
2013-08-13 21:52:13 +04:00
|
|
|
love:
|
|
|
|
|
2014-02-03 00:11:15 +04:00
|
|
|
learnDefer() // A quick detour to an important keyword.
|
2014-01-31 03:47:55 +04:00
|
|
|
learnInterfaces() // Good stuff coming up!
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2014-02-03 00:11:15 +04:00
|
|
|
func learnDefer() (ok bool) {
|
2014-04-16 18:06:58 +04:00
|
|
|
// Deferred statements are executed just before the function returns.
|
2014-02-03 00:11:15 +04:00
|
|
|
defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
|
|
|
|
defer fmt.Println("\nThis line is being printed first because")
|
2014-04-16 18:06:58 +04:00
|
|
|
// Defer is commonly used to close a file, so the function closing the file
|
2014-02-03 00:11:15 +04:00
|
|
|
// stays close to the function opening the file
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Define Stringer as an interface type with one method, String.
|
2013-08-13 21:52:13 +04:00
|
|
|
type Stringer interface {
|
2013-08-14 06:59:19 +04:00
|
|
|
String() string
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Define pair as a struct with two fields, ints named x and y.
|
2013-08-13 21:52:13 +04:00
|
|
|
type pair struct {
|
2013-08-14 06:59:19 +04:00
|
|
|
x, y int
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Define a method on type pair. Pair now implements Stringer.
|
|
|
|
func (p pair) String() string { // p is called the "receiver"
|
2013-08-14 06:59:19 +04:00
|
|
|
// Sprintf is another public function in package fmt.
|
|
|
|
// Dot syntax references fields of p.
|
|
|
|
return fmt.Sprintf("(%d, %d)", p.x, p.y)
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func learnInterfaces() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// Brace syntax is a "struct literal." It evaluates to an initialized
|
|
|
|
// struct. The := syntax declares and initializes p to this struct.
|
|
|
|
p := pair{3, 4}
|
2014-01-31 03:47:55 +04:00
|
|
|
fmt.Println(p.String()) // Call String method of p, of type pair.
|
|
|
|
var i Stringer // Declare i of interface type Stringer.
|
|
|
|
i = p // Valid because pair implements Stringer
|
2013-08-14 06:59:19 +04:00
|
|
|
// Call String method of i, of type Stringer. Output same as above.
|
|
|
|
fmt.Println(i.String())
|
|
|
|
|
|
|
|
// Functions in the fmt package call the String method to ask an object
|
|
|
|
// for a printable representation of itself.
|
2014-01-31 03:47:55 +04:00
|
|
|
fmt.Println(p) // Output same as above. Println calls String method.
|
|
|
|
fmt.Println(i) // Output same as above.
|
|
|
|
|
|
|
|
learnVariadicParams("great", "learning", "here!")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Functions can have variadic parameters.
|
|
|
|
func learnVariadicParams(myStrings ...interface{}) {
|
|
|
|
// Iterate each value of the variadic.
|
2014-05-12 00:33:08 +04:00
|
|
|
// The underbar here is ignoring the index argument of the array.
|
2014-01-31 03:47:55 +04:00
|
|
|
for _, param := range myStrings {
|
|
|
|
fmt.Println("param:", param)
|
|
|
|
}
|
2014-04-16 18:06:58 +04:00
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
// Pass variadic value as a variadic parameter.
|
|
|
|
fmt.Println("params:", fmt.Sprintln(myStrings...))
|
2013-08-14 06:59:19 +04:00
|
|
|
|
|
|
|
learnErrorHandling()
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func learnErrorHandling() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// ", ok" idiom used to tell if something worked or not.
|
|
|
|
m := map[int]string{3: "three", 4: "four"}
|
|
|
|
if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
|
|
|
|
fmt.Println("no one there")
|
|
|
|
} else {
|
|
|
|
fmt.Print(x) // x would be the value, if it were in the map.
|
|
|
|
}
|
|
|
|
// An error value communicates not just "ok" but more about the problem.
|
|
|
|
if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
|
2014-01-31 03:47:55 +04:00
|
|
|
// prints 'strconv.ParseInt: parsing "non-int": invalid syntax'
|
2013-08-14 06:59:19 +04:00
|
|
|
fmt.Println(err)
|
|
|
|
}
|
|
|
|
// We'll revisit interfaces a little later. Meanwhile,
|
|
|
|
learnConcurrency()
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// c is a channel, a concurrency-safe communication object.
|
2013-08-13 21:52:13 +04:00
|
|
|
func inc(i int, c chan int) {
|
2013-08-14 06:59:19 +04:00
|
|
|
c <- i + 1 // <- is the "send" operator when a channel appears on the left.
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// We'll use inc to increment some numbers concurrently.
|
|
|
|
func learnConcurrency() {
|
2013-08-14 06:59:19 +04:00
|
|
|
// Same make function used earlier to make a slice. Make allocates and
|
|
|
|
// initializes slices, maps, and channels.
|
|
|
|
c := make(chan int)
|
|
|
|
// Start three concurrent goroutines. Numbers will be incremented
|
|
|
|
// concurrently, perhaps in parallel if the machine is capable and
|
|
|
|
// properly configured. All three send to the same channel.
|
|
|
|
go inc(0, c) // go is a statement that starts a new goroutine.
|
|
|
|
go inc(10, c)
|
|
|
|
go inc(-805, c)
|
|
|
|
// Read three results from the channel and print them out.
|
|
|
|
// There is no telling in what order the results will arrive!
|
|
|
|
fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator.
|
|
|
|
|
2014-01-31 03:47:55 +04:00
|
|
|
cs := make(chan string) // Another channel, this one handles strings.
|
|
|
|
ccs := make(chan chan string) // A channel of string channels.
|
|
|
|
go func() { c <- 84 }() // Start a new goroutine just to send a value.
|
|
|
|
go func() { cs <- "wordy" }() // Again, for cs this time.
|
2013-08-14 06:59:19 +04:00
|
|
|
// Select has syntax like a switch statement but each case involves
|
|
|
|
// a channel operation. It selects a case at random out of the cases
|
|
|
|
// that are ready to communicate.
|
|
|
|
select {
|
2014-01-31 03:47:55 +04:00
|
|
|
case i := <-c: // The value received can be assigned to a variable,
|
2013-09-04 13:52:57 +04:00
|
|
|
fmt.Printf("it's a %T", i)
|
2014-01-31 03:47:55 +04:00
|
|
|
case <-cs: // or the value received can be discarded.
|
2013-08-14 06:59:19 +04:00
|
|
|
fmt.Println("it's a string")
|
2014-01-31 03:47:55 +04:00
|
|
|
case <-ccs: // Empty channel, not ready for communication.
|
2013-08-14 06:59:19 +04:00
|
|
|
fmt.Println("didn't happen.")
|
|
|
|
}
|
|
|
|
// At this point a value was taken from either c or cs. One of the two
|
|
|
|
// goroutines started above has completed, the other will remain blocked.
|
|
|
|
|
2014-04-16 18:06:58 +04:00
|
|
|
learnWebProgramming() // Go does it. You want to do it too.
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// A single function from package http starts a web server.
|
2013-08-13 21:52:13 +04:00
|
|
|
func learnWebProgramming() {
|
2014-01-31 03:47:55 +04:00
|
|
|
// First parameter of ListenAndServe is TCP address to listen to.
|
2013-08-14 06:59:19 +04:00
|
|
|
// Second parameter is an interface, specifically http.Handler.
|
|
|
|
err := http.ListenAndServe(":8080", pair{})
|
|
|
|
fmt.Println(err) // don't ignore errors
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
|
2013-08-14 01:12:54 +04:00
|
|
|
// Make pair an http.Handler by implementing its only method, ServeHTTP.
|
2013-08-13 21:52:13 +04:00
|
|
|
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2014-01-31 03:47:55 +04:00
|
|
|
// Serve data with a method of http.ResponseWriter.
|
2013-08-14 06:59:19 +04:00
|
|
|
w.Write([]byte("You learned Go in Y minutes!"))
|
2013-08-13 21:52:13 +04:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Further Reading
|
|
|
|
|
|
|
|
The root of all things Go is the [official Go web site](http://golang.org/).
|
|
|
|
There you can follow the tutorial, play interactively, and read lots.
|
|
|
|
|
|
|
|
The language definition itself is highly recommended. It's easy to read
|
|
|
|
and amazingly short (as language definitions go these days.)
|
|
|
|
|
2013-09-05 07:46:45 +04:00
|
|
|
On the reading list for students of Go is the [source code to the standard
|
|
|
|
library](http://golang.org/src/pkg/). Comprehensively documented, it
|
|
|
|
demonstrates the best of readable and understandable Go, Go style, and Go
|
|
|
|
idioms. Or you can click on a function name in [the
|
|
|
|
documentation](http://golang.org/pkg/) and the source code comes up!
|
2013-08-13 21:52:13 +04:00
|
|
|
|
2014-05-12 00:33:08 +04:00
|
|
|
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
|