break - an example



package main
import (
    "fmt"
    "time"
)
func main() {
    s := 0
    for {
        if s >= 5 { break }
        fmt.Println("s is:", s)
        s++
        time.Sleep(1000 * time.Millisecond)
    }
    fmt.Println("Break happened")
}

...and you get:
s is: 0
s is: 1
s is: 2
s is: 3
s is: 4
Break happened

print a, aa, aaa



package main
import (
    "fmt"
    "time"
)
func main() {
    s := "a"
    for ; s != "aaaaa"; {
        fmt.Println(s)
        s = s + "a"
        time.Sleep(1000 * time.Millisecond)
    }
}

Prints...
a
aa
aaa
aaaa

Here's a different way of doing this that I found on stackoverflow...
package main
import (
    "fmt"
    "bytes"
)
func main() {
    var buffer bytes.Buffer
    for i := 0; i < 10; i++{
        buffer.WriteString("a")
        fmt.Println(buffer.String())
    }
}

variables, pointers, memory location


Situation: For some reason, you need to access the address (or memory location) of variable i.

Solution:
package main

import "fmt"

func main() {
    var i int
    fmt.Println("address of i is:", &i, "value at address is ", *&i)

    x := 23
    fmt.Println("address of x is:", &x, "value at address is ", *&x)
}

Running go run a.go, I get...
address of i is: 0x18600110 value at address is  0
address of x is: 0x18600128 value at address is  23

clean reinstall go



I have ubuntu(linux) running on my daughter's pentium2 computer. When the kids want a faster computer for their games and homework, I let them use mine, and I use my daugther's.

I recently decided to play around with fedora on my daughter's pc... didn't like it and had to switch back to ubuntu. To make the long story short, I had to reinstall go. Here's how I did it.

  • download the golang tarball for my 32-bit ubuntu
  • sudo tar -C /usr/local -xzf go1.0.3.linux-286.tar.gz
  • Inside .bashrc, I included these:
    export GOROOT=/usr/local/go
    export PATH=$PATH:/usr/local/go/bin
    export GOOS=linux
    export GOARCH=386
    
  • create hello.go, then do go run hello.go, and I get hello world

unschooling



My son did not go to school today. He was doing a poor job pretending to be sick, but I chose to go along with his story. I was curious. Why did he not want to go to school?

Soon as we got home (I had to drive the wife and other kids to school), I found the reason why he wanted to stay at home.

Over the weekend, we got the playstation3 connected to the internet. Because of this, their playstation games opened up to the world of online gaming. I have four kids. They each have one hour of play time per turn.

My son, Marcus was the youngest of four children. Being so, his sisters played the games better than he did and was beating him all the time. To get better, he wanted to play more and figure out how to improve his game.

Marcus couldn't wait for his next turn to play when his sisters were around. The best way for him to improve was to stay at home while his sisters were away.

And that's why he did not go to school today. He said he was sick, but watching him play with the playstation, I knew what the real reason was.

My wife is upset that Marcus did not go to school again. She too, saw that he was pretending to be sick, but had to let him stay home--just in case he REALLY was sick.

I don't mind it if my kids want to skip school. In fact, I encourage it. I'd rather have them homeschooled acting on their interests and curiosity, than to spend hours in an institution that sapped the life out of you.

I hated school growing up. The stuff they teach you there (after reading and writing) may not be the things that you--the individual, should be learning.

I don't know how Marcus' interest with playstation is going to turn out for him in the future. What is important for me is that my kids know that I support them 100% in whatever it is that interests them--with integrity, of course.

while loops, an example



You want user to choose between 1 or 2. If they give you something else, the program loops asking them to choose between 1 or 2.

package main
import "fmt"

func main() {
    var choice int
    for choice != 1 && choice !=2 {
        fmt.Println("Pick a number between 1 or 2")
        fmt.Scanf("%d", &choice)
    }
    fmt.Printf("You chose %d\n", choice)
}

UPDATE:
Here's another one. Let's say user just finished a game. Ask to play again--yes or no?

package main
import "fmt"

func main() {
    choice := "y"
    for choice == "y" {
        fmt.Println("Play again? y or n")
        fmt.Scanf("%s", &choice)
    }
    fmt.Println("Bye!")
}

While loop



package main
import (
    "fmt"
    "time"
)

func main(){
    sum := 1
    for sum < 10 {
        sum += sum
        fmt.Println(sum)
        time.Sleep(300 * time.Millisecond)
    }
}
Remove the conditions and you get an infinite loop
import (
    "fmt"
    "time"
)

func main(){
    sum := 1
    for {
        sum += sum
        fmt.Println(sum)
        time.Sleep(300 * time.Millisecond)
    }
}

Guess the number game in golang



Source--IYOCGwP, Chapter 4 - Guess the Number - http://bit.ly/STSh0p

In python source code...

# This is a guess the number game.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
    print('Take a guess.') # There are four spaces in front of print.
    guess = input()
    guess = int(guess)
    guessesTaken = guessesTaken + 1
    if guess < number:
        print('Your guess is too low.') # There are eight spaces in front of print.
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break
if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

Same game, but this time, in Go source code...

// converting python games into golang
package main
import(
    "fmt"
    "math/rand"
    "time"
)

//this generates random number between given range
func xrand(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

func main() {
    var myname string
    myrand := xrand(1, 6)
    guessTaken := 0
    var guess int

    fmt.Println("Hello! What is your name?")
    fmt.Scanf("%s", &myname)
    fmt.Printf("Well, %s, I am thinking of a number between 1 and 6.\n", myname)
    
    //this is the while loop
    for guessTaken < 6 {
        fmt.Println("Take a guess...")
        fmt.Scanf("%d", &guess)
        guessTaken++
        if guess < myrand {
            fmt.Println("Your guess is too low.")
        }
        if guess > myrand {
            fmt.Println("Your guess is too high.")
        }
        if guess == myrand {
            break
        }
    }
    if guess == myrand {
        fmt.Printf("Good job %s! You guessed my number in %d tries\n", myname, guessTaken)
    } else {
        fmt.Printf("Nope. The number I had in mind was %d\n", myrand)
    }
}

*using else if...

if guess < myrand {
        fmt.Println("Your guess is too low.")
    } else if guess > myrand {
        fmt.Println("Your guess is too high.")
    } else {
        break
    }

generate random number in a given range



Total noob, teaching myself how to code.

I just spent an hour trying to figure out how to generate a random number from a given range using the go programming language(golang).

Here's the best that I've found so far...

package main
import(
    "fmt"
    "math/rand"
    "time"
)

func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

func main() {
    myrand := random(1, 6)
    fmt.Println(myrand)
}

func random defines how to create the random number.
rand.Seed ensures that the number that is generated is random(almost).
func main gives you that random number within any two positive numbers that you specify (in this case, 1 and 6).

golang heredocs?



Heredocs for the Go programming language?
package main
import "fmt"

func main() {
    myline := `
    the quick
    brown fox
    jumps over
    the lazy dog
    `
    fmt.Println(myline)
}

To Println multiple lines of strings in golang, use back ticks.

I am not sure if I got this right. I just read this somewhere on stackoverflow(i'll add the source link when I find it again) and decided to test it. The code above prints several lines, but with plenty of white space.
j@ime:~$ go run a.go

    the quick
    brown fox
    jumps over
    the lazy dog


I will look into how to make this work better... just multiple lines of string without the extra white space. I'll update when I figure it out.

Could not find app.yaml in "%s"



j@ime:~/myapp$ dev_appserver.py myapp
Traceback (most recent call last):
  File "/usr/local/bin/google_appengine/dev_appserver.py", line 171, in 
    run_file(__file__, globals())
  File "/usr/local/bin/google_appengine/dev_appserver.py", line 167, in run_file
    execfile(script_path, globals_)
  File "/usr/local/bin/google_appengine/google/appengine/tools/dev_appserver_main.py", line 747, in 
    sys.exit(main(sys.argv))
  File "/usr/local/bin/google_appengine/google/appengine/tools/dev_appserver_main.py", line 624, in main
    root_path, {}, default_partition=default_partition)
  File "/usr/local/bin/google_appengine/google/appengine/tools/dev_appserver.py", line 3355, in LoadAppConfig
    'Could not find app.yaml in "%s".' % (root_path,))
google.appengine.tools.dev_appserver.AppConfigNotFoundError: Could not find app.yaml in "myapp".

To fix this, i cd back to root, and again, ran dev_appserver.py myapp/
Allow dev_appserver to check for updates on startup? (Y/n): y
dev_appserver will check for updates on startup.  To change this setting, edit /home/j/.appcfg_nag
INFO     2012-11-09 04:12:38,938 appcfg.py:585] Checking for updates to the SDK.
INFO     2012-11-09 04:12:42,031 appcfg.py:619] This SDK release is newer than the advertised release.
WARNING  2012-11-09 04:12:42,031 dev_appserver.py:3560] The datastore file stub is deprecated, and
will stop being the default in a future release.
Append the --use_sqlite flag to use the new SQLite stub.

You can port your existing data using the --port_sqlite_data flag or
purge your previous test data with --clear_datastore.

WARNING  2012-11-09 04:12:42,032 datastore_file_stub.py:518] Could not read datastore data from /tmp/dev_appserver.datastore
WARNING  2012-11-09 04:12:42,033 simple_search_stub.py:950] Could not read search indexes from /tmp/dev_appserver.searchindexes
INFO     2012-11-09 04:12:42,202 dev_appserver_multiprocess.py:655] Running application dev~helloworld on port 8080: http://localhost:8080
INFO     2012-11-09 04:12:42,203 dev_appserver_multiprocess.py:657] Admin console is available at: http://localhost:8080/_ah/admin
INFO     2012-11-09 04:13:09,607 __init__.py:453] building _go_app
INFO     2012-11-09 04:13:10,170 __init__.py:429] running _go_app, HTTP port = 55273, API port = 34087
INFO     2012-11-09 04:13:10,292 dev_appserver.py:3092] "GET / HTTP/1.1" 200 -
INFO     2012-11-09 04:13:10,608 dev_appserver.py:3092] "GET /favicon.ico HTTP/1.1" 200 -
INFO     2012-11-09 04:13:10,615 dev_appserver.py:3092] "GET /favicon.ico HTTP/1.1" 200 -

Opening a new tab, on the addressbar, type in localhost:8080/, and I get Hello World.

%q



%q

Integers - %q a single-quoted character literal safely escaped with Go syntax.
Strings - %q a double-quoted string safely escaped with Go syntax
source - http://golang.org/pkg/fmt/
package main

import(
    "fmt"
    "strings"
)

func main() {
    fmt.Printf("fields are: %q\n", strings.Fields(" foo bar baz "))
}

...will give you:
fields are: ["foo" "bar" "baz"]

switch, time.Sleep



package main

import(
    "fmt"
    "time"
)

func main() {
    fmt.Println("When's Saturday?")
    today := time.Now().Weekday()

    switch time.Saturday {
    case today+0:
        fmt.Println("Today")
    case today+1:
        fmt.Println("Tomorrow")
    case today+2:
        fmt.Println("In two days")
    default:
        fmt.Println("Too far away")
    }
    time.Sleep(3000 * time.Millisecond)
    fmt.Println("Just woke up")
}

strings input output



This snippet prints str1 to the screen, waits for your input, then prints out that input...

package main
import "fmt"

func main() {
    var myname string
    str1 := "What is your name?"
    fmt.Println(str1)
    fmt.Scanf("%s", &myname)
    fmt.Println("Hello", myname)
}

...and a few more:
package main
import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("What is your favorite color?")
    var favoriteColor string
    fmt.Scanf("%s", &favoriteColor)
    fmt.Println("Fave color is", favoriteColor)
    fmt.Println("What is your favorite food?")
    var myfood string
    fmt.Scanf("%s", &myfood)
    fmt.Printf("I like %s too!\n", myfood)
    fmt.Printf("Wait two seconds please...\n")
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("Your favorite color is %s, and the food you like best is %q\n", favoriteColor, myfood)
}

Nosebleed tutorials



I am teaching myself golang from "A Tour of Go'... but it has been a nosebleed so far.

It's too technical and my mind can't grasp the concepts. My head is looking for more practical examples.

I am going to bookmark that site and use it for reference. In the meantime, I am going to google for practical golang tutorials.

Better yet, I'll convert basic python games code into golang and see how far I can go. It is going to be like driving a high-performance formula 1 race car through downtown traffic--I know.

This for me, is baby steps. Soon as I am comfortable with golang's grammar, I can start playing with scripting and system programming.

go: command not found



I am getting this error message after I installed go on a second computer--go: command not found.

This pc is running ubuntu 11.01. I was able to install go a few days ago using sudo apt-get install golang-stable.

I decided to do a fresh install, this time compiling from source so that go will be installed in $HOME/go.

After the compile and install, I do go run a.go and I get go: command not found. I'm going to google for a solution, then update this blog post how I fixed this.

UPDATE:
I couldn't figure it out. I chose to do a reinstall, using sudo apt-get install golang-stable.

To remove the tarball go install, I did sudo rm -rf go, as I read from http://weekly.golang.org/doc/install

It works, as I mentioned earlier. What's different is that golang was installed in /usr/lib/go. Just to be sure, I added export PATH=$PATH:/usr/lib/go/bin in my .bashrc

Hello world


I was bored the other day, and decided to try Go.

And I liked it--so far.

I am starting this blog so I can keep my notes, code snippets and anything else that is related to the Go Programming language.

package main
import "fmt"

func main() {
    fmt.Println("Hello world")
}