Learning go for perl programmers

Post on 13-Feb-2017

177 views 0 download

Transcript of Learning go for perl programmers

Learning Go for Perl Programmers

Fred MoyerSF Perl Mongers, 06082016

The Go Programming LanguageDeveloped at Google circa 2007

Goroutines (threads)

Channels (queues)

One way to format code (gofmt)

Hello SF.pm!package main

import "fmt"

func main() {

fmt.Println("Hello, サンフランシスコのPerlモンガー")

}

Hash || Object => Structtype Person struct {

id int // lowercase fields are not exported

email string // note no commas after variable type

Name string

HeightCentimeters float32 // camelCase convention

IsAlive bool // true or false, defaults to false

}

Hash || Object => Structvar famousActor = Person{

id: 1,

email: "jeff@goldblum.org",

Name: "Jeff Goldblum", // no single quotes

HeightCentimeters: 193.5,

IsAlive: true,

}

Hash || Object => Struct// we all knew this day would come

// perhaps in Independence Day: Resurgence?

// use the dot notation to make it happen

famousActor.IsAlive = false

Array => Slicevar tallActors []string

tallActors = append(tallActors, “Dolph Lundgren”)

tallActors[0] = “Richard Kiel”

tallActors[1] = “Chevy Chase” // error: index out of range

tallActors = append(tallActors, “Vince Vaughn”)

tallActorsCopy := make([]string, len(tallActors))

copy(tallActorsCopy, tallActors)

Array => Array// not used nearly as much as slices

var tenIntegers [10]int

fiveIntegers := [5]int{1,2,3,4,5}

lastThreeIntegers := fiveIntegers[2:] // outputs 3,4,5

firstTwoIntegers := fiveIntegers[:2] // outputs 1,2

Hash => Mapcountries := make(map[string]int)

countries[“Canada”] = 1

countries[“US”] = 2

canadaId = countries[“Canada”] // 1

delete(countries, “US”)

countries := map[string]int{“Canada”: 1, “US”: 2}

countryId, exists := countries[“Atlantis”] // exists == nil

Loopsfor i:= 0; i < 10; i++ {

fmt.Printf(“We’re going to 11”, i+1)

}

for i, actor := range []string{“Van Dam”, “Liam Neeson”} {

fmt.Printf(“#%d is %v”, i, actor) // %v default format

}

for _, actor := ... // _ ignores the loop iterator value

$@ => errbytesRead, err := w.Write([]byte{“data written to client”})

if err != nil {

log.WithField("err", err).Error("write to client failed")

}

var err error // built in error type

err.Error() // format error as a string

use => importimport (

"database/sql"

"encoding/json"

"flag"

"fmt"

)

sub foo => func foo (bar string, boo int)func httpEndpoint(world string) http.Handler {

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

bytesRead, _ := w.Write([]byte(

fmt.Sprintf(“Hello %v!”, world)))

return

}

}

t/test.t => main_test.gomain.go # file containing your code, ‘go run main.go’

main_test.go # unit test for main.go

go test # runs main_test.go, executes all tests

func TestSomething(t *testing.T) {

// do some stuff

if err != nil { t.Errorf("test failed %v", err) }

}

perldoc => godoc$ godoc fmt

use 'godoc cmd/fmt' for documentation on the fmt command

PACKAGE DOCUMENTATION

package fmt

import "fmt"

...

perldoc => godoc$ godoc fmt Sprintf

use 'godoc cmd/fmt' for documentation on the fmt command

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the

resulting string.

CPAN => https://golang.org/pkg/

cpanminus => go getgo get github.com/quipo/statsd

$ ls gocode/src/github.com/quipo/statsd/

LICENSE bufferedclient_test.go event

README.md client.go interface.go

bufferedclient.go client_test.go noopclient.go

PERL5LIB => GOPATH$ echo $GOPATH

/Users/phred/gocode

$ ls gocode/

bin pkg src

$ ls gocode/src/

github.com glenda golang.org

? => go build$ pwd

~/gocode/src/myorg/myapp

$ ls

main.go main_test.go

$ go build; ls

main.go main_test.go myapp

./myapp # binary executable you can relocate to same arch

queues => channelsc := make(chan string) // queue for string data type

hello := “Hello SF.pm”

c <- hello

// ...

fmt.Println(<-c) // prints “Hello.SF.pm”

bufferedChannel := make(chan string, 2) // buffers 2 strings

// channels are first class citizens of Go

threads => goroutineshello := “Hello SF.pm”

go myFunc(hello)

func myFunc(myString string) {

fmt.Println(myString)

}

// spawns an asynchronous thread which executes a function

// goroutines are first class citizens of Go

Tour of Golang web placeshttps://golang.org/

https://tour.golang.org/welcome/1

https://golang.org/pkg/

https://groups.google.com/forum/#!forum/golang-nuts

Questions?