Go for Dummies (WIP 0.

2)

License

Go for Dummies (WIP 0.2) ........................................... 1
Introduction................................................................................... 1
Contributions ................................................................................. 2
Go Compiler and Tool-set Installation ................................................ 2
Go Environment Variables ............................................................. 2
Downloading Go source ................................................................ 3
Installing Go ............................................................................... 3
Intro to programming with Go .......................................................... 4
Hello World.................................................................................... 4
Using the Go compiler ..................................................................... 5
Amd64 systems........................................................................... 5
386 systems ............................................................................... 5
ARM systems .............................................................................. 6
Makefiles....................................................................................... 6
Commentary.................................................................................. 6
Names .......................................................................................... 7
Package Names ........................................................................... 7
Interface Names .......................................................................... 7
Mixed Caps ................................................................................. 7
Types ........................................................................................... 8
List of types ............................................................................. 8
Variables ....................................................................................... 8
Exercise 1:............................................................................... 9
Operators ...................................................................................... 9
List of operators ..................................................................... 10
Exercise 2:............................................................................. 11
Exercise 3:............................................................................. 11
If & Else ...................................................................................... 11
Exercise 4:............................................................................. 12
Switch ........................................................................................ 12
Exercise 5:............................................................................. 13
For loop ...................................................................................... 13
Exercise 6:............................................................................. 14
Functions .................................................................................... 14
Input from console ....................................................................... 15

Introduction
I decided to write this tutorial document, because it seemed that there's no resources for
newbies who want to learn programming with go the language by google.
Go is simple, fast, safe, concurrent, open source and fun. Go compilers produce fast
code fast, typical builds take a fraction of second, when whole applications run nearly as
quickly as c or c++. Go is general purpose language with systems programming in mind.
Programs are packages and packages allow efficient management of dependencies. Go
at the moment uses general compile/link model to generate executable applications, so
it does not produce any code when the applications are run like java. You can find other
tutorials from Golangs own site like tutorial and Effective Go also you can find
information about the standard packages from pkg. You can also find some extra
resources from cat-v go site

wait did you really rea d even one name in it? Well not that i care that much.The book will have code samples in this style all around. Go Environment Variables First you need to set few Environment variables into your . Around the book will be similar code examples.bashrc Add to the end the following. In this case Go to binary. i suggest you to inspect them well and even try to compile it yourself.bashrc so open it. Go Compiler and Tool-set Installation Now that you have quickly jumped over the contribut or list we can continue on installing compiler. $ gedit ~/. Hello World Example ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ fmt. but how would you do it if you don't have the compiler installed yet. #Google Go Env Vars export GOROOT=~/go/src export GOOS=linux export GOARCH=386 export GOBIN=$HOME/go/bin PATH=${PATH}:$HOME/go/bin . You can install Go compiler at the moment to Linux and Mac.com. use Comments if you want to comment something. if you want to edit this document. Binary is the language what the computers speak and execute and we write in Go what we want the computer to execute. but thank these people who have helped with this book. contact TMKCodes@gmail. Actually before we start installation i will explain few things. Compiler is like an human translator who is first listening to another language and then speaking the same in other language. Well next we will install the compiler.Println("Hello World by Go!\n") } ----------------------------------------------------------------------------------------------------------Anyway now you saw the first application of Go which prints "Hello World by Go!" to your console if you would run this. Contributions Place Holder! Contributors. Compiler is a computer program which transforms your source code into another language.

Once you have it checkout. .bashrc with. requires python. C standard libraries. $ hg clone -r release https://go. $ cd ~/go/src/src Now you can execute the all. bison.bash Iif all goes well it should finish with message like this. but please wait.com and get it from there. $ source ./all.bash $ . awk and the text editor ed installed. you can move to installing Go compiler. make. #ubuntu $ sudo apt-get install bison gcc libc6-dev ed gawk make To build the tool-set you have to move into the GOROOT folder.cd . If you do not have it installed yet then use method for your system or you can go to mercurial.. $ mkdir go $ cd go $ mkdir bin Now you can run the command that fetch the source of go from mercurial repository. --. #ubuntu $ sudo apt-get install mercurial #Python Easy Install. 0 unexpected bugs N will be different version number. Os X users install them as part of XCode.googlecode. If you have building problems contact people at #Go-Nuts. On Linux./test N known bugs. python-setuptools and python-dev packages $ sudo easy_install mercurial Create folders. Installing Go The Go Compiler and Tools are written in C so you need to have GCC.Now you have to reset your .com/hg/ $GOROOT This might take some time depending on your network speed.bashrc Downloading Go source After you have done this we can download the source of go with mercurial.

At the moment working with Go is painful with text editor and console.Intro to programming with Go We should know. ----------------------------------------------------------------------------------------------------------import "PackageName" ----------------------------------------------------------------------------------------------------------Every program has an main function which is started when the program starts and ended when the program ends. ----------------------------------------------------------------------------------------------------------fmt. So don't think you can use awesome IDE like Visual Studio with Go. Go will for sure change and so will this guide accordingly. So what you can do with Go? at the moment you can easily write system utilities and server side services. like when you press enter while editing text files. there's no windows compiler for go yet or not sure if even one comes. . first i will explain how the Hello World code works and then we will try compiling it. ----------------------------------------------------------------------------------------------------------func main(){ } ----------------------------------------------------------------------------------------------------------Inside the main function is code that runs. ----------------------------------------------------------------------------------------------------------package PackageName ----------------------------------------------------------------------------------------------------------You can include other packages in your program by importing them.Println("Hello World by Go!\n") ----------------------------------------------------------------------------------------------------------Now we can move to compiling the Hello World code. In the Hello World code we are using function PrintF function from the fmt package and making it to print "Hello World by Go!NewLine" the \n creates new line. Go is really fresh language and there is not much tools for it done yet. So lets start. well for start. Hello World You need to define package name for every file y ou create with the keyword. well some of the old time programmers love working this way.

$ 8l HelloWorld.6 Run it. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ fmt. Once you are in the same folder you can use the following commands to compile and run your code Amd64 systems Compile the program with this command. $ . $ 6g HelloWorld. Next you have to open console and move to the folder where the code is located at. $ .Println("Hello World by Go!\n") } ----------------------------------------------------------------------------------------------------------Now you have your code.Using the Go compiler First create an new file called HelloWorld. $ 6l HelloWorld.go Link it with this command.out 386 systems Compile the program with this command. $ 8g HelloWorld.8 Run it.go and write the hello world code into it.go Link it with this command./6./8.out .

The syntax of the regular expressions accepted is: regexp: concatenation { '|' concatenation } concatenation: { closure } closure: term [ '*' | '+' | '?' ] term: '^' '$' '. You can come backwards and check material if you have forgotten. $ 5g HelloWorld.ARM systems Compile the program with this command. These lessons will move fast if you do not practice at all and by just reading this book you will not become a programmer you need to experience it even if it feels hard. Block comments appear mostly as package comments and are useful for disabling blocks of code.go Link it with this command. The godoc tool processes go source files to extract documentation from them to HTML format.' character '[' [ '^' ]character-ranges ']' . Package Block Comment ----------------------------------------------------------------------------------------------------------/* The regexp package implements a simple library for regular expressions. Every package should have an Package comment. $ . After every lesson i will give exercises to help you on your practicing. $ 5l HelloWorld.out Now you are able to compile and run your programs.5 Run it. Now we will move to our programming lessons. Makefiles To make compiling simpler lets learn to use makefiles. Into the same folder where you created your Hello World file./5. create file named makefile. Commentary Go has C-style commentary line comments // and block comments /* */.

Mixed Caps The convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names. ----------------------------------------------------------------------------------------------------------// The path package implements utility routines for // manipulating slash-separated filename paths. single-word names.Ring which is the definition of a constructor in Go would normally be called NewRing.Printf. . but since Ring is the only type exported by the package. Use the package structure to help you choose good names. there should be no need for underscores or mixedCaps. So therefore it's useful to spend little time with this topic.'(' regexp ')' */ package regexp ----------------------------------------------------------------------------------------------------------Line comment. Names Names are very important in Go like for instance the visibility of the name is effected by it. Package Names The package name becomes accessor after importing it like ----------------------------------------------------------------------------------------------------------import "fmt" ----------------------------------------------------------------------------------------------------------When importing a package the program can use the packages contents like smf. The function to make new instances of ring. ----------------------------------------------------------------------------------------------------------Comments do not need extra graphics like stars or anything. and since the package is called ring. it's called just New. importer. Do not worry of name collisions as Go can select new name if Collision happens. writer. such as reader. they are way better like this. Clients of the package see that as ring. packages are given lower case. By convention. Interface Names One method interfaces are named by the method name and -er suffix.New.

as many characters as you assign to it adding u before the type name like uint32 will make the type unsigned. decimal value no recurring decimals int16. size. Int16 is integer type which can store 16 bytes. List of types Keyword. Lets look at sample. 32 bits. but you can reassign it. which represent the appropriate value for the machine. This was small brief of types. 64 bits. the amount of data you can store into variable changes. Depending on the type of the variable. depends on your system. decimal value no recurring decimals float. 8 bits. 32 bits. ufloat64. 16 bits. value true or false string. but are immutable values. decimal value no recurring decimals int. You first declare variable and then assign an value to it. ----------------------------------------------------------------------------------------------------------- . Works with decimal values. So basically you could declare string value and assign text into it. i) } ----------------------------------------------------------------------------------------------------------In this code you can see we declare variable named i with the type int16 and assign 10 to it. Then we use smf.Types Go has types such as int and float. 8 bits. decimal value no recurring decimals int8. Go has string types which are not just arrays of byte values. Unsinged types are uint8. decimal with recurring decimals float32. description byte. decimal value no recurring decimals int32. Once you have built an string value it's impossible to modify it. decimal with recurring decimals bool. depends on your system. decimal value no recurring decimals int64. you will learn more about types while we get to variables. 32 bits. Variables Variables are facilities to store values. int8 has synonym called byte. float64. decimal with recurring decimals float64.Println to print int16: 10. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ var i int16 = 10 fmt.Println("Int16: ". There is also explicitly-sized types like int8.

" by Go!") } ----------------------------------------------------------------------------------------------------------In here we declare variable named text with string type and assign Hello World into it and print it. So now here is an exercise for you. Then print them with smf.Println.package main import "fmt" func main(){ var text string = "Hello World" fmt. Well like most languages Go supports +. Exercise 1: Create variables called MyName and Money. You can also declare variables in shorter way. Assign to MyName your name and to Money how much money you have. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ . but are you now thinking how to use operators./. It happens this way: VarName := Type(Value) It is shorter than var VarName type = value. Operators You now know how to declare variables and assign values to them.Println(text.Println("value of i is ". So lets now write an example how we use these operators.* and other kind of operators. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ i := int32(15) fmt. short declaration can be used when declaring other stuff than variables too. i) } ----------------------------------------------------------------------------------------------------------In here we declare variable in the way that we use the short declaration of Go.-.

Println it is access operator. this.25 fmt. Modifying values happens so we assign to i the value of i * 25. in ftm. i + 25) fmt. but simply you will be using different operators all the time. As you might notice if you compile this code the values are not correct as we are modifying the value of i and then using operator in the print too to modify the value.Println("Value of i was 15. well they are correct if we keep the code like. i) of i was ".Subtraction * Multiplication / Division += Assignment by addition -= Assignment by subtraction *= Assignment by multiplication /= Assignment by division Comparison operators == equal to .25) fmt.Println("Value of i was ".var i int32 = 15 i = i . " it is now: ".Println("Value of i was 15. i .25. it is now: ". i * 25. " it is now: ". i + 25. i) } ----------------------------------------------------------------------------------------------------------In this code we declare variable named i and assign 15 to it. First time you used an operator was with the hello world when you used the . " it is now: ". i) of i was ". but we do not want to do it like this. i) of i was ". i * 25) fmt. i . So lets modify this. Then we use different operators to modify the value. it is now: ". i + 25.Println("Value i = i / 25 fmt. " it is now: ". ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ var i int32 = 15 fmt.Println("Value i = i * 25 fmt.Println("Value of i was ".Println("Value of i was ". List of operators Arithmetic operators + Addition .Println("Value i = i + 25 fmt. i . " it is now: ". " it is now: ". i * 25. i / 25) } ----------------------------------------------------------------------------------------------------------Now the code is outputting the values we want.25.

with this statements you can compare values.Println(i. So lets show how it works ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ var i int32 = 15 var a int32 = 16 if i < a { // Do something. a) } else { // Do something. a) } } ----------------------------------------------------------------------------------------------------------In this example we check if i is smaller than a. Output how many apples was left and how many apples everyone has.. Martin.!= not equal to < less than > greater than <= less or equal than > greater or equal than Other operators = Assignment Please update this if you know more operators of Go -Toni Korpela 2/21/10 1:40 PM Exercise 2: Write an application where Jack. " is smaller than ". fmt. ftm. Martin takes 1. " is larger than ". Joe takes 1. Joe share 7 apples..Println(i. Jack takes 2. If & Else Now is time to introduce you to if and else statements. Daniel takes 3. Exercise 3: Modify exercise 2 so that Daniel gives 1 apple to Joe and half apple to Martin. Daniel. If it is we print "15 is smaller than 16" if .

ftm. these work same way as if statements. a) } } ----------------------------------------------------------------------------------------------------------In this code we did else if statement. .... So how would we use else if then? I will show ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ var i int32 = 20 var a int32 = 16 if i < a { // Do something. Exercise 4: Create an application where Joe throws 1 rock and if it his print "Joe broke a Microsoft's window!" if it does not hit print "Joe missed the Microsoft's window!". but are easier to use if you have many options. Switch Now that you know if and else statements. to make more comparison checks. In this case we never go to else part of the code unless we modify the values.it is not we print "15 is smaller than 16".Println(i. Lets look at an example.. lets look at switches. fmt. " is larger than ".Println(i. " is smaller than ". " is same as ". a) } else if i == a { // Do something.Println(i. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main(){ var i int32 = 20 var a int32 = 16 switch { case i > a: { // Do Something. See else if i == a fmt. a) } else { // Do something.

. a) } case i < a: // Do Something.. Exercise 5: Modify the exercise 4 to use switch instead of if-else if-else statements. condition. For Loop ----------------------------------------------------------------------------------------------------------for init. post { } ----------------------------------------------------------------------------------------------------------While Loop ----------------------------------------------------------------------------------------------------------for condition { } ----------------------------------------------------------------------------------------------------------Forever loop ----------------------------------------------------------------------------------------------------------for { } ----------------------------------------------------------------------------------------------------------Now lets show an example while using for loop. but we can also use blocks to add more stuff to be run if the case matches.. For loop In Go for loop is bit different to other languages as it unifies For and While loop and there is no Do-While loop. " is greater than ". Loop means that it continues running the code inside the loop block until the condition is met over and over again. case i == a: // Do something.} fmt. } ----------------------------------------------------------------------------------------------------------You notice that with a switch we can have one line after case which is run.Println(i.

but try to write an program where the program has 20 apples and Max. you are already quite ready to write programs. Joe. but think what kind of functions are needed. Print when they take and eat apples and when the loop ends print who has apples left. Exercise 6: You have learned about if-else statements. They will also eat apples and eating an apple takes 2 rounds of the loop. i < x. but you can try it yourself. Tim take apples from it until there is none left. ----------------------------------------------------------------------------------------------------------package main import "fmt" func main() { x := int32(20) i := int32(1) for i < x { fmt. Functions Functions are really useful.Println("Hello World times by %d". but do not let them take any of the apples same time. i) i++ } } ----------------------------------------------------------------------------------------------------------This is the while loop and i wont even show the forever loop as it will run forever until the program is forcibly executed.----------------------------------------------------------------------------------------------------------package main import "fmt" func main() { x := int32(20) for i := int32(0). Like function which prints the sent parameter is not . i++ { fmt.Println("Hello World times by ". Now lets use the while loop. makes your main function less messy. i) } } ----------------------------------------------------------------------------------------------------------This code will print "Hello World times by N" 20 times. you can write simple text games already. switches and loops. So please use them as much as you want. Functions are even useful for reusing the code. but lets not go that far yet.

so every interaction with input and output happens with stdin and stdout.50)) fmt.TrimSpace(result) .stdin) result. Well lets look now at console input. as it would just wrap the fmt. _ := in. height int32) (int32) { square := int32(width*height) return square } func main() { square := int32(calcSquare(30.ReadString('\n') text := strings. ----------------------------------------------------------------------------------------------------------package main import ( "fmt" "bufio" "os" "strings" ) func main() { fmt.Print function. so lets now show an working function ----------------------------------------------------------------------------------------------------------package main import "fmt" // Here is an function which calculates the square func calcSquare(width int32.needed. In go function can also return multiple values unlike language like C. how would you get input from the user? In Unix systems everything is a file.Println("Write something:") in := bufio.Println("Square is ". square) } ----------------------------------------------------------------------------------------------------------- Input from console So now you know how to use functions and how to make functions lets look bit more at standard functions.NewReader(os. ----------------------------------------------------------------------------------------------------------func functionName (parameters) (return types) { return V } ----------------------------------------------------------------------------------------------------------This is example of how functions are done.

NewReader(os. _ := in. err := strconv. You might notice the underline on the code. os.Atoi(text) // Convert the string to int fmt. In this case that variable which we are ignoring is error variable. This code takes input from the user and stores it into the text variable as string. :P .stdin) result.Println(text) // Print the input as string number.Println(number.fmt. bufio.Println(text) } ----------------------------------------------------------------------------------------------------------In this code we are importing more packages.TrimSpace(result) fmt. It is keyword to ignore variable from multi result functions.ReadString('\n') text := strings. err) // Print the input as int } ----------------------------------------------------------------------------------------------------------Now you are totally ready to build console text games. ----------------------------------------------------------------------------------------------------------package main import ( "fmt" "bufio" "os" "strings" "strconv" ) func main() { fmt.Println("Write something:") in := bufio. strings. You could convert the string to int or float with little more work and i will show now how that would happen.

Sign up to vote on this title
UsefulNot useful