@paddyforan // paddy.io
talks.paddy.io/gophper
… is what you expect me to say.
j.mp/devtribal
(…and C had unicorns and magic…)
(…and C had decades of programming languages to pilfer shamelessly from…)
Code should be self-documenting!
Go code does exactly what it says on the page.
Be as concise as possible without sacrificing clarity.
See bit.ly/gotools1 and bit.ly/gotools2
Files don’t matter, packages do.
package fmt
“main” is a special package
package main
package main
import "github.com/DramaFever/pan"
class Everything
{
public $status = 'awesome!';
public function getStatus() {
echo 'everything is '.$this->status;
}
}
type Everything struct {
status string
}
func (e Everything) GetStatus() {
fmt.Printf("Everything is %s", e.status)
}
type Lego struct {
Length int
Width int
}
type Person struct {
Name string
}
type LegoPerson struct {
Lego
Person
}
benny := new(LegoPerson)
benny.Length = 1
benny.Width = 2
benny.Name = "Benny"
var thisWillAlwaysBeAString string
var masterBuilder bool
masterBuilder = true
batmansFavouriteColour := "black"
batmansFavouriteColour = "black and sometimes gray"
i := 0
for i := 0; i < 3; i++ {
fmt.Println(i+1)
}
fmt.Printf("outside for loop: %d", i)
1
2
3
outside for loop: 0
class Kragle
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
}
var ThisIsTotallyPublic string
var onlyICanSeeThis int
type myAwesomeType struct {
SuperCoolAttribute string
}
func NewAwesomeType() myAwesomeType {
return myAwesomeType{SuperCoolAttribute:"This is so cool!"}
}
fmt.Println(NewAwesomeType().SuperCoolAttribute)
for _, x := range []string{"this", "is", "so", "cool!"} {
fmt.Println(x)
}
(Even pointers)
type Gophers struct {
Count int
}
func Convert(g Gophers) {
g.Count++
}
gophers := Gophers{}
Convert(gophers)
fmt.Println(gophers.Count)
Convert(gophers)
fmt.Println(gophers.Count)
Zeroes all the way down
type Gophers struct {
Count int
}
func Convert(g *Gophers) {
g.Count++
}
gophers := Gophers{}
Convert(&gophers)
fmt.Println(gophers.Count) // 1
Convert(&gophers)
fmt.Println(gophers.Count) // 2
Sharing and reusing code is a single command
import "github.com/DramaFever/pan"
func HandleRequest(w http.ResponseWriter, r http.Request)
type ThingDoer interface{
DoTheThing() bool
}
type ThingDoerImplementation struct{}
func (t ThingDoerImplementation) DoTheThing() bool {
fmt.Println("Did the thing!")
return true
}
You can think of channels as really lightweight queues.
func Get(url string, resp chan *http.Response, wg *sync.WaitGroup) {
defer wg.Done()
r, _ := http.Get(url)
resp <- r
}
func WaitAndClose(wg *sync.WaitGroup, resp chan *http.Response) {
wg.Wait()
close(resp)
}
resp := make(chan *http.Response)
wg := new(sync.WaitGroup)
urls := []string{"http://google.com", "http://dramafever.com",
"http://paddy.io", "http://tek.phparch.com"}
for _, u := range urls {
wg.Add(1)
go Get(u, resp, wg)
}
go WaitAndClose(wg, resp)
for r := range resp {
fmt.Println(r.Status)
}