From 4dc83f3ccc22e7bdf7b4ba2842ad63d7f8ae0e97 Mon Sep 17 00:00:00 2001
From: Eli Bendersky
package main -+
package main
import "fmt" -+
import "fmt"
func main() { -+
func main() {
int
s means 0
s.
- var a [5]int - fmt.Println("emp:", a) -+
var a [5]int
+ fmt.Println("emp:", a)
int
s means 0
s.
- a[4] = 100 - fmt.Println("set:", a) - fmt.Println("get:", a[4]) -+
a[4] = 100
+ fmt.Println("set:", a)
+ fmt.Println("get:", a[4])
int
s means 0
s.
- fmt.Println("len:", len(a)) -+
fmt.Println("len:", len(a))
- b := [5]int{1, 2, 3, 4, 5} - fmt.Println("dcl:", b) -+
b := [5]int{1, 2, 3, 4, 5}
+ fmt.Println("dcl:", b)
- var twoD [2][3]int - for i := 0; i < 2; i++ { - for j := 0; j < 3; j++ { - twoD[i][j] = i + j - } - } - fmt.Println("2d: ", twoD) -} -+
var twoD [2][3]int
+ for i := 0; i < 2; i++ {
+ for j := 0; j < 3; j++ {
+ twoD[i][j] = i + j
+ }
+ }
+ fmt.Println("2d: ", twoD)
+}
fmt.Println
.
-$ go run arrays.go -emp: [0 0 0 0 0] -set: [0 0 0 0 100] -get: 100 -len: 5 -dcl: [1 2 3 4 5] -2d: [[0 1 2] [1 2 3]]+
$ go run arrays.go
+emp: [0 0 0 0 0]
+set: [0 0 0 0 100]
+get: 100
+len: 5
+dcl: [1 2 3 4 5]
+2d: [[0 1 2] [1 2 3]]
package main -+
package main
import ( - "fmt" - "sync" - "sync/atomic" -) -+
import (
+ "fmt"
+ "sync"
+ "sync/atomic"
+)
func main() { -+
func main() {
- var ops uint64 -+
var ops uint64
- var wg sync.WaitGroup -+
var wg sync.WaitGroup
- for i := 0; i < 50; i++ { - wg.Add(1) -+
for i := 0; i < 50; i++ {
+ wg.Add(1)
ops
counter with the
go func() { - for c := 0; c < 1000; c++ { -+
go func() {
+ for c := 0; c < 1000; c++ {
ops
counter with the
atomic.AddUint64(&ops, 1) - } - wg.Done() - }() - } -+
atomic.AddUint64(&ops, 1)
+ }
+ wg.Done()
+ }()
+ }
ops
counter with the
- wg.Wait() -+
wg.Wait()
- fmt.Println("ops:", ops) -} -+
fmt.Println("ops:", ops)
+}
-race
flag.
-$ go run atomic-counters.go -ops: 50000+
$ go run atomic-counters.go
+ops: 50000
package main -+
package main
-import ( - b64 "encoding/base64" - "fmt" -) -+
import (
+ b64 "encoding/base64"
+ "fmt"
+)
func main() { -+
func main() {
- data := "abc123!?$*&()'-=@~" -+
data := "abc123!?$*&()'-=@~"
string
to that type.
- sEnc := b64.StdEncoding.EncodeToString([]byte(data)) - fmt.Println(sEnc) -+
sEnc := b64.StdEncoding.EncodeToString([]byte(data))
+ fmt.Println(sEnc)
- sDec, _ := b64.StdEncoding.DecodeString(sEnc) - fmt.Println(string(sDec)) - fmt.Println() -+
sDec, _ := b64.StdEncoding.DecodeString(sEnc)
+ fmt.Println(string(sDec))
+ fmt.Println()
- uEnc := b64.URLEncoding.EncodeToString([]byte(data)) - fmt.Println(uEnc) - uDec, _ := b64.URLEncoding.DecodeString(uEnc) - fmt.Println(string(uDec)) -} -+
uEnc := b64.URLEncoding.EncodeToString([]byte(data))
+ fmt.Println(uEnc)
+ uDec, _ := b64.URLEncoding.DecodeString(uEnc)
+ fmt.Println(string(uDec))
+}
-$ go run base64-encoding.go -YWJjMTIzIT8kKiYoKSctPUB+ -abc123!?$*&()'-=@~+
$ go run base64-encoding.go
+YWJjMTIzIT8kKiYoKSctPUB+
+abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB- -abc123!?$*&()'-=@~+
YWJjMTIzIT8kKiYoKSctPUB-
+abc123!?$*&()'-=@~
package main -+
package main
import "fmt" -+
import "fmt"
func main() { -+
func main() {
- messages := make(chan string, 2) -+
messages := make(chan string, 2)
- messages <- "buffered" - messages <- "channel" -+
messages <- "buffered"
+ messages <- "channel"
- fmt.Println(<-messages) - fmt.Println(<-messages) -} -+
fmt.Println(<-messages)
+ fmt.Println(<-messages)
+}
$ go run channel-buffering.go -buffered -channel+
$ go run channel-buffering.go
+buffered
+channel
package main -+
package main
import "fmt" -+
import "fmt"
-func ping(pings chan<- string, msg string) { - pings <- msg -} -+
func ping(pings chan<- string, msg string) {
+ pings <- msg
+}
-func pong(pings <-chan string, pongs chan<- string) { - msg := <-pings - pongs <- msg -} -+
func pong(pings <-chan string, pongs chan<- string) {
+ msg := <-pings
+ pongs <- msg
+}
func main() { - pings := make(chan string, 1) - pongs := make(chan string, 1) - ping(pings, "passed message") - pong(pings, pongs) - fmt.Println(<-pongs) -} -+
func main() {
+ pings := make(chan string, 1)
+ pongs := make(chan string, 1)
+ ping(pings, "passed message")
+ pong(pings, pongs)
+ fmt.Println(<-pongs)
+}
$ go run channel-directions.go -passed message+
$ go run channel-directions.go
+passed message
package main -+
package main
import ( - "fmt" - "time" -) -+
import (
+ "fmt"
+ "time"
+)
-func worker(done chan bool) { - fmt.Print("working...") - time.Sleep(time.Second) - fmt.Println("done") -+
func worker(done chan bool) {
+ fmt.Print("working...")
+ time.Sleep(time.Second)
+ fmt.Println("done")
- done <- true -} -+
done <- true
+}
func main() { -+
func main() {
- done := make(chan bool, 1) - go worker(done) -+
done := make(chan bool, 1)
+ go worker(done)
- <-done -} -+
<-done
+}
$ go run channel-synchronization.go -working...done+
$ go run channel-synchronization.go
+working...done
package main -+
package main
import "fmt" -+
import "fmt"
func main() { -+
func main() {
- messages := make(chan string) -+
messages := make(chan string)
- go func() { messages <- "ping" }() -+
go func() { messages <- "ping" }()
- msg := <-messages - fmt.Println(msg) -} -+
msg := <-messages
+ fmt.Println(msg)
+}
-$ go run channels.go -ping+
$ go run channels.go
+ping
package main -+
package main
import "fmt" -+
import "fmt"
close
the jobs
channel.
-func main() { - jobs := make(chan int, 5) - done := make(chan bool) -+
func main() {
+ jobs := make(chan int, 5)
+ done := make(chan bool)
- go func() { - for { - j, more := <-jobs - if more { - fmt.Println("received job", j) - } else { - fmt.Println("received all jobs") - done <- true - return - } - } - }() -+
go func() {
+ for {
+ j, more := <-jobs
+ if more {
+ fmt.Println("received job", j)
+ } else {
+ fmt.Println("received all jobs")
+ done <- true
+ return
+ }
+ }
+ }()
- for j := 1; j <= 3; j++ { - jobs <- j - fmt.Println("sent job", j) - } - close(jobs) - fmt.Println("sent all jobs") -+
for j := 1; j <= 3; j++ {
+ jobs <- j
+ fmt.Println("sent job", j)
+ }
+ close(jobs)
+ fmt.Println("sent all jobs")
- <-done -} -+
<-done
+}
$ go run closing-channels.go -sent job 1 -received job 1 -sent job 2 -received job 2 -sent job 3 -received job 3 -sent all jobs -received all jobs+
$ go run closing-channels.go
+sent job 1
+received job 1
+sent job 2
+received job 2
+sent job 3
+received job 3
+sent all jobs
+received all jobs
package main -+
package main
import "fmt" -+
import "fmt"
-func intSeq() func() int { - i := 0 - return func() int { - i++ - return i - } -} -+
func intSeq() func() int {
+ i := 0
+ return func() int {
+ i++
+ return i
+ }
+}
func main() { -+
func main() {
nextInt
.
- nextInt := intSeq() -+
nextInt := intSeq()
- fmt.Println(nextInt()) - fmt.Println(nextInt()) - fmt.Println(nextInt()) -+
fmt.Println(nextInt())
+ fmt.Println(nextInt())
+ fmt.Println(nextInt())
- newInts := intSeq() - fmt.Println(newInts()) -} -+
newInts := intSeq()
+ fmt.Println(newInts())
+}
$ go run closures.go -1 -2 -3 -1+
$ go run closures.go
+1
+2
+3
+1
go run hello.go
uses run
and
package main -+
package main
go run hello.go
uses run
and
import ( - "fmt" - "os" -) -+
import (
+ "fmt"
+ "os"
+)
go run hello.go
uses run
and
func main() { -+
func main() {
- argsWithProg := os.Args - argsWithoutProg := os.Args[1:] -+
argsWithProg := os.Args
+ argsWithoutProg := os.Args[1:]
- arg := os.Args[3] -+
arg := os.Args[3]
fmt.Println(argsWithProg) - fmt.Println(argsWithoutProg) - fmt.Println(arg) -} -+
fmt.Println(argsWithProg)
+ fmt.Println(argsWithoutProg)
+ fmt.Println(arg)
+}
go build
first.
-$ go build command-line-arguments.go -$ ./command-line-arguments a b c d -[./command-line-arguments a b c d] -[a b c d] -c+
$ go build command-line-arguments.go
+$ ./command-line-arguments a b c d
+[./command-line-arguments a b c d]
+[a b c d]
+c
package main -+
package main
-import ( - "flag" - "fmt" -) -+
import (
+ "flag"
+ "fmt"
+)
func main() { -+
func main() {
- wordPtr := flag.String("word", "foo", "a string") -+
wordPtr := flag.String("word", "foo", "a string")
word
flag.
- numbPtr := flag.Int("numb", 42, "an int") - forkPtr := flag.Bool("fork", false, "a bool") -+
numbPtr := flag.Int("numb", 42, "an int")
+ forkPtr := flag.Bool("fork", false, "a bool")
- var svar string - flag.StringVar(&svar, "svar", "bar", "a string var") -+
var svar string
+ flag.StringVar(&svar, "svar", "bar", "a string var")
- flag.Parse() -+
flag.Parse()
- fmt.Println("word:", *wordPtr) - fmt.Println("numb:", *numbPtr) - fmt.Println("fork:", *forkPtr) - fmt.Println("svar:", svar) - fmt.Println("tail:", flag.Args()) -} -+
fmt.Println("word:", *wordPtr)
+ fmt.Println("numb:", *numbPtr)
+ fmt.Println("fork:", *forkPtr)
+ fmt.Println("svar:", svar)
+ fmt.Println("tail:", flag.Args())
+}
-$ go build command-line-flags.go
+ $ go build command-line-flags.go
-$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag -word: opt -numb: 7 -fork: true -svar: flag -tail: []+
$ ./command-line-flags -word=opt -numb=7 -fork -svar=flag
+word: opt
+numb: 7
+fork: true
+svar: flag
+tail: []
-$ ./command-line-flags -word=opt -word: opt -numb: 42 -fork: false -svar: bar -tail: []+
$ ./command-line-flags -word=opt
+word: opt
+numb: 42
+fork: false
+svar: bar
+tail: []
-$ ./command-line-flags -word=opt a1 a2 a3 -word: opt -... -tail: [a1 a2 a3]+
$ ./command-line-flags -word=opt a1 a2 a3
+word: opt
+...
+tail: [a1 a2 a3]
-$ ./command-line-flags -word=opt a1 a2 a3 -numb=7 -word: opt -numb: 42 -fork: false -svar: bar -tail: [a1 a2 a3 -numb=7]+
$ ./command-line-flags -word=opt a1 a2 a3 -numb=7
+word: opt
+numb: 42
+fork: false
+svar: bar
+tail: [a1 a2 a3 -numb=7]
-$ ./command-line-flags -h -Usage of ./command-line-flags: - -fork=false: a bool - -numb=42: an int - -svar="bar": a string var - -word="foo": a string+
$ ./command-line-flags -h
+Usage of ./command-line-flags:
+ -fork=false: a bool
+ -numb=42: an int
+ -svar="bar": a string var
+ -word="foo": a string
-$ ./command-line-flags -wat -flag provided but not defined: -wat -Usage of ./command-line-flags: -...+
$ ./command-line-flags -wat
+flag provided but not defined: -wat
+Usage of ./command-line-flags:
+...
package main -+
package main
import ( - "flag" - "fmt" - "os" -) -+
import (
+ "flag"
+ "fmt"
+ "os"
+)
func main() { -+
func main() {
- fooCmd := flag.NewFlagSet("foo", flag.ExitOnError) - fooEnable := fooCmd.Bool("enable", false, "enable") - fooName := fooCmd.String("name", "", "name") -+
fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
+ fooEnable := fooCmd.Bool("enable", false, "enable")
+ fooName := fooCmd.String("name", "", "name")
- barCmd := flag.NewFlagSet("bar", flag.ExitOnError) - barLevel := barCmd.Int("level", 0, "level") -+
barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
+ barLevel := barCmd.Int("level", 0, "level")
- if len(os.Args) < 2 { - fmt.Println("expected 'foo' or 'bar' subcommands") - os.Exit(1) - } -+
if len(os.Args) < 2 {
+ fmt.Println("expected 'foo' or 'bar' subcommands")
+ os.Exit(1)
+ }
- switch os.Args[1] { -+
switch os.Args[1] {
- case "foo": - fooCmd.Parse(os.Args[2:]) - fmt.Println("subcommand 'foo'") - fmt.Println(" enable:", *fooEnable) - fmt.Println(" name:", *fooName) - fmt.Println(" tail:", fooCmd.Args()) - case "bar": - barCmd.Parse(os.Args[2:]) - fmt.Println("subcommand 'bar'") - fmt.Println(" level:", *barLevel) - fmt.Println(" tail:", barCmd.Args()) - default: - fmt.Println("expected 'foo' or 'bar' subcommands") - os.Exit(1) - } -} -+
case "foo":
+ fooCmd.Parse(os.Args[2:])
+ fmt.Println("subcommand 'foo'")
+ fmt.Println(" enable:", *fooEnable)
+ fmt.Println(" name:", *fooName)
+ fmt.Println(" tail:", fooCmd.Args())
+ case "bar":
+ barCmd.Parse(os.Args[2:])
+ fmt.Println("subcommand 'bar'")
+ fmt.Println(" level:", *barLevel)
+ fmt.Println(" tail:", barCmd.Args())
+ default:
+ fmt.Println("expected 'foo' or 'bar' subcommands")
+ os.Exit(1)
+ }
+}
$ go build command-line-subcommands.go
+ $ go build command-line-subcommands.go
-$ ./command-line-subcommands foo -enable -name=joe a1 a2 -subcommand 'foo' - enable: true - name: joe - tail: [a1 a2]+
$ ./command-line-subcommands foo -enable -name=joe a1 a2
+subcommand 'foo'
+ enable: true
+ name: joe
+ tail: [a1 a2]
-$ ./command-line-subcommands bar -level 8 a1 -subcommand 'bar' - level: 8 - tail: [a1]+
$ ./command-line-subcommands bar -level 8 a1
+subcommand 'bar'
+ level: 8
+ tail: [a1]
-$ ./command-line-subcommands bar -enable a1 -flag provided but not defined: -enable -Usage of bar: - -level int - level+
$ ./command-line-subcommands bar -enable a1
+flag provided but not defined: -enable
+Usage of bar:
+ -level int
+ level
package main -+
package main
import ( - "fmt" - "math" -) -+
import (
+ "fmt"
+ "math"
+)
-const s string = "constant" -+
const s string = "constant"
func main() { - fmt.Println(s) -+
func main() {
+ fmt.Println(s)
- const n = 500000000 -+
const n = 500000000
- const d = 3e20 / n - fmt.Println(d) -+
const d = 3e20 / n
+ fmt.Println(d)
- fmt.Println(int64(d)) -+
fmt.Println(int64(d))
- fmt.Println(math.Sin(n)) -} -+
fmt.Println(math.Sin(n))
+}
$ go run constant.go -constant -6e+11 -600000000000 --0.28470407323754404+
$ go run constant.go
+constant
+6e+11
+600000000000
+-0.28470407323754404
-package main -+
package main
import ( - "fmt" - "net/http" - "time" -) -+
import (
+ "fmt"
+ "net/http"
+ "time"
+)
func hello(w http.ResponseWriter, req *http.Request) { -+
func hello(w http.ResponseWriter, req *http.Request) {
Context()
method.
- ctx := req.Context() - fmt.Println("server: hello handler started") - defer fmt.Println("server: hello handler ended") -+
ctx := req.Context()
+ fmt.Println("server: hello handler started")
+ defer fmt.Println("server: hello handler ended")
- select { - case <-time.After(10 * time.Second): - fmt.Fprintf(w, "hello\n") - case <-ctx.Done(): -+
select {
+ case <-time.After(10 * time.Second):
+ fmt.Fprintf(w, "hello\n")
+ case <-ctx.Done():
- err := ctx.Err() - fmt.Println("server:", err) - internalError := http.StatusInternalServerError - http.Error(w, err.Error(), internalError) - } -} -+
err := ctx.Err()
+ fmt.Println("server:", err)
+ internalError := http.StatusInternalServerError
+ http.Error(w, err.Error(), internalError)
+ }
+}
func main() { -+
func main() {
- http.HandleFunc("/hello", hello) - http.ListenAndServe(":8090", nil) -} -+
http.HandleFunc("/hello", hello)
+ http.ListenAndServe(":8090", nil)
+}
-$ go run context-in-http-servers.go &
+ $ go run context-in-http-servers.go &
-$ curl localhost:8090/hello -server: hello handler started -^C -server: context canceled -server: hello handler ended+
$ curl localhost:8090/hello
+server: hello handler started
+^C
+server: context canceled
+server: hello handler ended
defer
is often used where e.g.
package main -+
package main
defer
is often used where e.g.
import ( - "fmt" - "os" -) -+
import (
+ "fmt"
+ "os"
+)
defer
.
-func main() { -+
func main() {
main
), after
- f := createFile("/tmp/defer.txt") - defer closeFile(f) - writeFile(f) -} -+
f := createFile("/tmp/defer.txt")
+ defer closeFile(f)
+ writeFile(f)
+}
main
), after
func createFile(p string) *os.File { - fmt.Println("creating") - f, err := os.Create(p) - if err != nil { - panic(err) - } - return f -} -+
func createFile(p string) *os.File {
+ fmt.Println("creating")
+ f, err := os.Create(p)
+ if err != nil {
+ panic(err)
+ }
+ return f
+}
main
), after
func writeFile(f *os.File) { - fmt.Println("writing") - fmt.Fprintln(f, "data") -+
func writeFile(f *os.File) {
+ fmt.Println("writing")
+ fmt.Fprintln(f, "data")
main
), after
}
-
+ }
func closeFile(f *os.File) { - fmt.Println("closing") - err := f.Close() -+
func closeFile(f *os.File) {
+ fmt.Println("closing")
+ err := f.Close()
if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } -} -+
if err != nil {
+ fmt.Fprintf(os.Stderr, "error: %v\n", err)
+ os.Exit(1)
+ }
+}
-$ go run defer.go -creating -writing -closing+
$ go run defer.go
+creating
+writing
+closing
package main -+
package main
import ( - "fmt" - "os" - "path/filepath" -) -+
import (
+ "fmt"
+ "os"
+ "path/filepath"
+)
func check(e error) { - if e != nil { - panic(e) - } -} -+
func check(e error) {
+ if e != nil {
+ panic(e)
+ }
+}
func main() { -+
func main() {
- err := os.Mkdir("subdir", 0755) - check(err) -+
err := os.Mkdir("subdir", 0755)
+ check(err)
- defer os.RemoveAll("subdir") -+
defer os.RemoveAll("subdir")
- createEmptyFile := func(name string) { - d := []byte("") - check(os.WriteFile(name, d, 0644)) - } -+
createEmptyFile := func(name string) {
+ d := []byte("")
+ check(os.WriteFile(name, d, 0644))
+ }
createEmptyFile("subdir/file1") -+
createEmptyFile("subdir/file1")
mkdir -p
.
- err = os.MkdirAll("subdir/parent/child", 0755) - check(err) -+
err = os.MkdirAll("subdir/parent/child", 0755)
+ check(err)
mkdir -p
.
createEmptyFile("subdir/parent/file2") - createEmptyFile("subdir/parent/file3") - createEmptyFile("subdir/parent/child/file4") -+
createEmptyFile("subdir/parent/file2")
+ createEmptyFile("subdir/parent/file3")
+ createEmptyFile("subdir/parent/child/file4")
os.DirEntry
objects.
- c, err := os.ReadDir("subdir/parent") - check(err) -+
c, err := os.ReadDir("subdir/parent")
+ check(err)
os.DirEntry
objects.
fmt.Println("Listing subdir/parent") - for _, entry := range c { - fmt.Println(" ", entry.Name(), entry.IsDir()) - } -+
fmt.Println("Listing subdir/parent")
+ for _, entry := range c {
+ fmt.Println(" ", entry.Name(), entry.IsDir())
+ }
cd
.
- err = os.Chdir("subdir/parent/child") - check(err) -+
err = os.Chdir("subdir/parent/child")
+ check(err)
- c, err = os.ReadDir(".") - check(err) -+
c, err = os.ReadDir(".")
+ check(err)
fmt.Println("Listing subdir/parent/child") - for _, entry := range c { - fmt.Println(" ", entry.Name(), entry.IsDir()) - } -+
fmt.Println("Listing subdir/parent/child")
+ for _, entry := range c {
+ fmt.Println(" ", entry.Name(), entry.IsDir())
+ }
- err = os.Chdir("../../..") - check(err) -+
err = os.Chdir("../../..")
+ check(err)
- fmt.Println("Visiting subdir") - err = filepath.Walk("subdir", visit) -} -+
fmt.Println("Visiting subdir")
+ err = filepath.Walk("subdir", visit)
+}
filepath.Walk
.
-func visit(p string, info os.FileInfo, err error) error { - if err != nil { - return err - } - fmt.Println(" ", p, info.IsDir()) - return nil -} -+
func visit(p string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ fmt.Println(" ", p, info.IsDir())
+ return nil
+}
filepath.Walk
.
$ go run directories.go -Listing subdir/parent - child true - file2 false - file3 false -Listing subdir/parent/child - file4 false -Visiting subdir - subdir true - subdir/file1 false - subdir/parent true - subdir/parent/child true - subdir/parent/child/file4 false - subdir/parent/file2 false - subdir/parent/file3 false+
$ go run directories.go
+Listing subdir/parent
+ child true
+ file2 false
+ file3 false
+Listing subdir/parent/child
+ file4 false
+Visiting subdir
+ subdir true
+ subdir/file1 false
+ subdir/parent true
+ subdir/parent/child true
+ subdir/parent/child/file4 false
+ subdir/parent/file2 false
+ subdir/parent/file3 false
-package main -+
package main
_ "embe
-
-import (
- "embed"
-)
-
+ import (
+ "embed"
+)
@@ -67,10 +63,8 @@ Go source file. This directive embeds the contents of the file into the
-
-//go:embed folder/single_file.txt
-var fileString string
-
+ //go:embed folder/single_file.txt
+var fileString string
@@ -81,10 +75,8 @@ Go source file. This directive embeds the contents of the file into the
-
-//go:embed folder/single_file.txt
-var fileByte []byte
-
+ //go:embed folder/single_file.txt
+var fileByte []byte
@@ -97,11 +89,9 @@ implements a simple virtual file system.
-
-//go:embed folder/single_file.txt
-//go:embed folder/*.hash
-var folder embed.FS
-
+ //go:embed folder/single_file.txt
+//go:embed folder/*.hash
+var folder embed.FS
@@ -111,8 +101,7 @@ implements a simple virtual file system.
- func main() {
-
+ func main() {
@@ -123,10 +112,8 @@ implements a simple virtual file system.
-
- print(fileString)
- print(string(fileByte))
-
+ print(fileString)
+ print(string(fileByte))
@@ -137,10 +124,8 @@ implements a simple virtual file system.
-
- content1, _ := folder.ReadFile("folder/file1.hash")
- print(string(content1))
-
+ content1, _ := folder.ReadFile("folder/file1.hash")
+ print(string(content1))
@@ -150,10 +135,9 @@ implements a simple virtual file system.
- content2, _ := folder.ReadFile("folder/file2.hash")
- print(string(content2))
-}
-
+ content2, _ := folder.ReadFile("folder/file2.hash")
+ print(string(content2))
+}
@@ -170,11 +154,10 @@ this example can only be run on your local machine.)
-
-$ mkdir -p folder
-$ echo "hello go" > folder/single_file.txt
-$ echo "123" > folder/file1.hash
-$ echo "456" > folder/file2.hash
+ $ mkdir -p folder
+$ echo "hello go" > folder/single_file.txt
+$ echo "123" > folder/file1.hash
+$ echo "456" > folder/file2.hash
@@ -184,11 +167,11 @@ this example can only be run on your local machine.)
- $ go run embed-directive.go
-hello go
-hello go
-123
-456
+ $ go run embed-directive.go
+hello go
+hello go
+123
+456
diff --git a/public/environment-variables b/public/environment-variables
index f0d0e5e..eb0ccb7 100644
--- a/public/environment-variables
+++ b/public/environment-variables
@@ -45,8 +45,7 @@ Let’s look at how to set, get, and list environment variables.

- package main
-
+ package main
@@ -56,12 +55,11 @@ Let’s look at how to set, get, and list environment variables.
- import (
- "fmt"
- "os"
- "strings"
-)
-
+ import (
+ "fmt"
+ "os"
+ "strings"
+)
@@ -71,8 +69,7 @@ Let’s look at how to set, get, and list environment variables.
- func main() {
-
+ func main() {
@@ -86,11 +83,9 @@ environment.
-
- os.Setenv("FOO", "1")
- fmt.Println("FOO:", os.Getenv("FOO"))
- fmt.Println("BAR:", os.Getenv("BAR"))
-
+ os.Setenv("FOO", "1")
+ fmt.Println("FOO:", os.Getenv("FOO"))
+ fmt.Println("BAR:", os.Getenv("BAR"))
@@ -104,14 +99,12 @@ get the key and value. Here we print all the keys.
-
- fmt.Println()
- for _, e := range os.Environ() {
- pair := strings.SplitN(e, "=", 2)
- fmt.Println(pair[0])
- }
-}
-
+ fmt.Println()
+ for _, e := range os.Environ() {
+ pair := strings.SplitN(e, "=", 2)
+ fmt.Println(pair[0])
+ }
+}
@@ -128,10 +121,9 @@ for FOO
that we set in the program, but that
-
-$ go run environment-variables.go
-FOO: 1
-BAR:
+ $ go run environment-variables.go
+FOO: 1
+BAR:
@@ -143,12 +135,11 @@ particular machine.
-
-TERM_PROGRAM
-PATH
-SHELL
-...
-FOO
+ TERM_PROGRAM
+PATH
+SHELL
+...
+FOO
@@ -160,11 +151,10 @@ program picks that value up.
-
-$ BAR=2 go run environment-variables.go
-FOO: 1
-BAR: 2
-...
+ $ BAR=2 go run environment-variables.go
+FOO: 1
+BAR: 2
+...
diff --git a/public/epoch b/public/epoch
index 890b66e..8e7d9a7 100644
--- a/public/epoch
+++ b/public/epoch
@@ -45,8 +45,7 @@ Here’s how to do it in Go.

- package main
-
+ package main
@@ -56,11 +55,10 @@ Here’s how to do it in Go.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -70,8 +68,7 @@ Here’s how to do it in Go.
- func main() {
-
+ func main() {
@@ -84,10 +81,8 @@ milliseconds or nanoseconds, respectively.
-
- now := time.Now()
- fmt.Println(now)
-
+ now := time.Now()
+ fmt.Println(now)
@@ -97,10 +92,9 @@ milliseconds or nanoseconds, respectively.
- fmt.Println(now.Unix())
- fmt.Println(now.UnixMilli())
- fmt.Println(now.UnixNano())
-
+ fmt.Println(now.Unix())
+ fmt.Println(now.UnixMilli())
+ fmt.Println(now.UnixNano())
@@ -112,11 +106,9 @@ since the epoch into the corresponding time
.
-
- fmt.Println(time.Unix(now.Unix(), 0))
- fmt.Println(time.Unix(0, now.UnixNano()))
-}
-
+ fmt.Println(time.Unix(now.Unix(), 0))
+ fmt.Println(time.Unix(0, now.UnixNano()))
+}
@@ -130,13 +122,13 @@ since the epoch into the corresponding time
.
- $ go run epoch.go
-2012-10-31 16:13:58.292387 +0000 UTC
-1351700038
-1351700038292
-1351700038292387000
-2012-10-31 16:13:58 +0000 UTC
-2012-10-31 16:13:58.292387 +0000 UTC
+ $ go run epoch.go
+2012-10-31 16:13:58.292387 +0000 UTC
+1351700038
+1351700038292
+1351700038292387000
+2012-10-31 16:13:58 +0000 UTC
+2012-10-31 16:13:58.292387 +0000 UTC
diff --git a/public/errors b/public/errors
index 9444171..ab084ad 100644
--- a/public/errors
+++ b/public/errors
@@ -49,8 +49,7 @@ non-error tasks.

- package main
-
+ package main
@@ -60,11 +59,10 @@ non-error tasks.
- import (
- "errors"
- "fmt"
-)
-
+ import (
+ "errors"
+ "fmt"
+)
@@ -76,10 +74,8 @@ have type error
, a built-in interface.
-
-func f1(arg int) (int, error) {
- if arg == 42 {
-
+ func f1(arg int) (int, error) {
+ if arg == 42 {
@@ -91,9 +87,7 @@ with the given error message.
-
- return -1, errors.New("can't work with 42")
-
+ return -1, errors.New("can't work with 42")
@@ -103,8 +97,7 @@ with the given error message.
- }
-
+ }
@@ -116,10 +109,8 @@ there was no error.
-
- return arg + 3, nil
-}
-
+ return arg + 3, nil
+}
@@ -133,12 +124,10 @@ to explicitly represent an argument error.
-
-type argError struct {
- arg int
- prob string
-}
-
+ type argError struct {
+ arg int
+ prob string
+}
@@ -148,10 +137,9 @@ to explicitly represent an argument error.
- func (e *argError) Error() string {
- return fmt.Sprintf("%d - %s", e.arg, e.prob)
-}
-
+ func (e *argError) Error() string {
+ return fmt.Sprintf("%d - %s", e.arg, e.prob)
+}
@@ -161,9 +149,8 @@ to explicitly represent an argument error.
- func f2(arg int) (int, error) {
- if arg == 42 {
-
+ func f2(arg int) (int, error) {
+ if arg == 42 {
@@ -176,12 +163,10 @@ fields arg
and prob
.
-
- return -1, &argError{arg, "can't work with it"}
- }
- return arg + 3, nil
-}
-
+ return -1, &argError{arg, "can't work with it"}
+ }
+ return arg + 3, nil
+}
@@ -191,8 +176,7 @@ fields arg
and prob
.
- func main() {
-
+ func main() {
@@ -206,22 +190,20 @@ idiom in Go code.
-
- for _, i := range []int{7, 42} {
- if r, e := f1(i); e != nil {
- fmt.Println("f1 failed:", e)
- } else {
- fmt.Println("f1 worked:", r)
- }
- }
- for _, i := range []int{7, 42} {
- if r, e := f2(i); e != nil {
- fmt.Println("f2 failed:", e)
- } else {
- fmt.Println("f2 worked:", r)
- }
- }
-
+ for _, i := range []int{7, 42} {
+ if r, e := f1(i); e != nil {
+ fmt.Println("f1 failed:", e)
+ } else {
+ fmt.Println("f1 worked:", r)
+ }
+ }
+ for _, i := range []int{7, 42} {
+ if r, e := f2(i); e != nil {
+ fmt.Println("f2 failed:", e)
+ } else {
+ fmt.Println("f2 worked:", r)
+ }
+ }
@@ -235,14 +217,12 @@ assertion.
-
- _, e := f2(42)
- if ae, ok := e.(*argError); ok {
- fmt.Println(ae.arg)
- fmt.Println(ae.prob)
- }
-}
-
+ _, e := f2(42)
+ if ae, ok := e.(*argError); ok {
+ fmt.Println(ae.arg)
+ fmt.Println(ae.prob)
+ }
+}
@@ -256,13 +236,13 @@ assertion.
- $ go run errors.go
-f1 worked: 10
-f1 failed: can't work with 42
-f2 worked: 10
-f2 failed: 42 - can't work with it
-42
-can't work with it
+ $ go run errors.go
+f1 worked: 10
+f1 failed: can't work with 42
+f2 worked: 10
+f2 failed: 42 - can't work with it
+42
+can't work with it
diff --git a/public/execing-processes b/public/execing-processes
index 6e9c5a3..083d11e 100644
--- a/public/execing-processes
+++ b/public/execing-processes
@@ -50,8 +50,7 @@ function.

- package main
-
+ package main
@@ -61,12 +60,11 @@ function.
- import (
- "os"
- "os/exec"
- "syscall"
-)
-
+ import (
+ "os"
+ "os/exec"
+ "syscall"
+)
@@ -76,8 +74,7 @@ function.
- func main() {
-
+ func main() {
@@ -91,12 +88,10 @@ we’ll use exec.LookPath
to find it (probably
-
- binary, lookErr := exec.LookPath("ls")
- if lookErr != nil {
- panic(lookErr)
- }
-
+ binary, lookErr := exec.LookPath("ls")
+ if lookErr != nil {
+ panic(lookErr)
+ }
@@ -110,9 +105,7 @@ be the program name.
-
- args := []string{"ls", "-a", "-l", "-h"}
-
+ args := []string{"ls", "-a", "-l", "-h"}
@@ -125,9 +118,7 @@ environment.
-
- env := os.Environ()
-
+ env := os.Environ()
@@ -142,13 +133,11 @@ value.
-
- execErr := syscall.Exec(binary, args, env)
- if execErr != nil {
- panic(execErr)
- }
-}
-
+ execErr := syscall.Exec(binary, args, env)
+ if execErr != nil {
+ panic(execErr)
+ }
+}
@@ -163,12 +152,11 @@ value.
-
-$ go run execing-processes.go
-total 16
-drwxr-xr-x 4 mark 136B Oct 3 16:29 .
-drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
--rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.go
+ $ go run execing-processes.go
+total 16
+drwxr-xr-x 4 mark 136B Oct 3 16:29 .
+drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
+-rw-r--r-- 1 mark 1.3K Oct 3 16:28 execing-processes.go
diff --git a/public/exit b/public/exit
index 902ba78..ff7073c 100644
--- a/public/exit
+++ b/public/exit
@@ -39,8 +39,7 @@ status.

- package main
-
+ package main
@@ -50,11 +49,10 @@ status.
- import (
- "fmt"
- "os"
-)
-
+ import (
+ "fmt"
+ "os"
+)
@@ -64,8 +62,7 @@ status.
- func main() {
-
+ func main() {
@@ -77,9 +74,7 @@ this fmt.Println
will never be called.
-
- defer fmt.Println("!")
-
+ defer fmt.Println("!")
@@ -90,10 +85,8 @@ this fmt.Println
will never be called.
-
- os.Exit(3)
-}
-
+ os.Exit(3)
+}
@@ -123,9 +116,8 @@ will be picked up by go
and printed.
-
-$ go run exit.go
-exit status 3
+ $ go run exit.go
+exit status 3
@@ -137,11 +129,10 @@ the status in the terminal.
-
-$ go build exit.go
-$ ./exit
-$ echo $?
-3
+ $ go build exit.go
+$ ./exit
+$ echo $?
+3
diff --git a/public/file-paths b/public/file-paths
index d129bde..bfa4b61 100644
--- a/public/file-paths
+++ b/public/file-paths
@@ -35,9 +35,7 @@ between operating systems; dir/file
on Linux vs.

-
-package main
-
+ package main
@@ -47,12 +45,11 @@ between operating systems; dir/file
on Linux vs.
- import (
- "fmt"
- "path/filepath"
- "strings"
-)
-
+ import (
+ "fmt"
+ "path/filepath"
+ "strings"
+)
@@ -62,8 +59,7 @@ between operating systems; dir/file
on Linux vs.
- func main() {
-
+ func main() {
@@ -76,10 +72,8 @@ and constructs a hierarchical path from them.
-
- p := filepath.Join("dir1", "dir2", "filename")
- fmt.Println("p:", p)
-
+ p := filepath.Join("dir1", "dir2", "filename")
+ fmt.Println("p:", p)
@@ -94,10 +88,8 @@ and directory changes.
-
- fmt.Println(filepath.Join("dir1//", "filename"))
- fmt.Println(filepath.Join("dir1/../dir1", "filename"))
-
+ fmt.Println(filepath.Join("dir1//", "filename"))
+ fmt.Println(filepath.Join("dir1/../dir1", "filename"))
@@ -110,10 +102,8 @@ return both in the same call.
-
- fmt.Println("Dir(p):", filepath.Dir(p))
- fmt.Println("Base(p):", filepath.Base(p))
-
+ fmt.Println("Dir(p):", filepath.Dir(p))
+ fmt.Println("Base(p):", filepath.Base(p))
@@ -124,10 +114,8 @@ return both in the same call.
-
- fmt.Println(filepath.IsAbs("dir/file"))
- fmt.Println(filepath.IsAbs("/dir/file"))
-
+ fmt.Println(filepath.IsAbs("dir/file"))
+ fmt.Println(filepath.IsAbs("/dir/file"))
@@ -137,8 +125,7 @@ return both in the same call.
- filename := "config.json"
-
+ filename := "config.json"
@@ -150,10 +137,8 @@ can split the extension out of such names with Ext
.
-
- ext := filepath.Ext(filename)
- fmt.Println(ext)
-
+ ext := filepath.Ext(filename)
+ fmt.Println(ext)
@@ -165,9 +150,7 @@ use strings.TrimSuffix
.
-
- fmt.Println(strings.TrimSuffix(filename, ext))
-
+ fmt.Println(strings.TrimSuffix(filename, ext))
@@ -180,13 +163,11 @@ be made relative to base.
-
- rel, err := filepath.Rel("a/b", "a/b/t/file")
- if err != nil {
- panic(err)
- }
- fmt.Println(rel)
-
+ rel, err := filepath.Rel("a/b", "a/b/t/file")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(rel)
@@ -196,13 +177,12 @@ be made relative to base.
- rel, err = filepath.Rel("a/b", "a/c/t/file")
- if err != nil {
- panic(err)
- }
- fmt.Println(rel)
-}
-
+ rel, err = filepath.Rel("a/b", "a/c/t/file")
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println(rel)
+}
@@ -216,18 +196,18 @@ be made relative to base.
- $ go run file-paths.go
-p: dir1/dir2/filename
-dir1/filename
-dir1/filename
-Dir(p): dir1/dir2
-Base(p): filename
-false
-true
-.json
-config
-t/file
-../c/t/file
+ $ go run file-paths.go
+p: dir1/dir2/filename
+dir1/filename
+dir1/filename
+Dir(p): dir1/dir2
+Base(p): filename
+false
+true
+.json
+config
+t/file
+../c/t/file
diff --git a/public/for b/public/for
index e5b9674..987ade2 100644
--- a/public/for
+++ b/public/for
@@ -43,8 +43,7 @@ some basic types of for
loops.

- package main
-
+ package main
@@ -54,8 +53,7 @@ some basic types of for
loops.
- import "fmt"
-
+ import "fmt"
@@ -65,8 +63,7 @@ some basic types of for
loops.
- func main() {
-
+ func main() {
@@ -77,13 +74,11 @@ some basic types of for
loops.
-
- i := 1
- for i <= 3 {
- fmt.Println(i)
- i = i + 1
- }
-
+ i := 1
+ for i <= 3 {
+ fmt.Println(i)
+ i = i + 1
+ }
@@ -94,11 +89,9 @@ some basic types of for
loops.
-
- for j := 7; j <= 9; j++ {
- fmt.Println(j)
- }
-
+ for j := 7; j <= 9; j++ {
+ fmt.Println(j)
+ }
@@ -111,12 +104,10 @@ the enclosing function.
-
- for {
- fmt.Println("loop")
- break
- }
-
+ for {
+ fmt.Println("loop")
+ break
+ }
@@ -128,15 +119,13 @@ the loop.
-
- for n := 0; n <= 5; n++ {
- if n%2 == 0 {
- continue
- }
- fmt.Println(n)
- }
-}
-
+ for n := 0; n <= 5; n++ {
+ if n%2 == 0 {
+ continue
+ }
+ fmt.Println(n)
+ }
+}
@@ -150,17 +139,17 @@ the loop.
- $ go run for.go
-1
-2
-3
-7
-8
-9
-loop
-1
-3
-5
+ $ go run for.go
+1
+2
+3
+7
+8
+9
+loop
+1
+3
+5
diff --git a/public/functions b/public/functions
index 74e7302..87a3a04 100644
--- a/public/functions
+++ b/public/functions
@@ -43,8 +43,7 @@ functions with a few different examples.

- package main
-
+ package main
@@ -54,8 +53,7 @@ functions with a few different examples.
- import "fmt"
-
+ import "fmt"
@@ -67,9 +65,7 @@ their sum as an int
.
-
-func plus(a int, b int) int {
-
+ func plus(a int, b int) int {
@@ -82,10 +78,8 @@ expression.
-
- return a + b
-}
-
+ return a + b
+}
@@ -99,11 +93,9 @@ declares the type.
-
-func plusPlus(a, b, c int) int {
- return a + b + c
-}
-
+ func plusPlus(a, b, c int) int {
+ return a + b + c
+}
@@ -113,8 +105,7 @@ declares the type.
- func main() {
-
+ func main() {
@@ -126,10 +117,8 @@ declares the type.
-
- res := plus(1, 2)
- fmt.Println("1+2 =", res)
-
+ res := plus(1, 2)
+ fmt.Println("1+2 =", res)
@@ -139,10 +128,9 @@ declares the type.
- res = plusPlus(1, 2, 3)
- fmt.Println("1+2+3 =", res)
-}
-
+ res = plusPlus(1, 2, 3)
+ fmt.Println("1+2+3 =", res)
+}
@@ -156,9 +144,9 @@ declares the type.
- $ go run functions.go
-1+2 = 3
-1+2+3 = 6
+ $ go run functions.go
+1+2 = 3
+1+2+3 = 6
diff --git a/public/generics b/public/generics
index 721f0f7..adee897 100644
--- a/public/generics
+++ b/public/generics
@@ -43,8 +43,7 @@

- package main
-
+ package main
@@ -54,8 +53,7 @@
- import "fmt"
-
+ import "fmt"
@@ -73,15 +71,13 @@ restricted in any way (any
is an alias for interface{}
-
-func MapKeys[K comparable, V any](m map[K]V) []K {
- r := make([]K, 0, len(m))
- for k := range m {
- r = append(r, k)
- }
- return r
-}
-
+ func MapKeys[K comparable, V any](m map[K]V) []K {
+ r := make([]K, 0, len(m))
+ for k := range m {
+ r = append(r, k)
+ }
+ return r
+}
@@ -93,11 +89,9 @@ singly-linked list with values of any type.
-
-type List[T any] struct {
- head, tail *element[T]
-}
-
+ type List[T any] struct {
+ head, tail *element[T]
+}
@@ -107,11 +101,10 @@ singly-linked list with values of any type.
- type element[T any] struct {
- next *element[T]
- val T
-}
-
+ type element[T any] struct {
+ next *element[T]
+ val T
+}
@@ -124,17 +117,15 @@ parameters in place. The type is List[T]
, not List
.
-
-func (lst *List[T]) Push(v T) {
- if lst.tail == nil {
- lst.head = &element[T]{val: v}
- lst.tail = lst.head
- } else {
- lst.tail.next = &element[T]{val: v}
- lst.tail = lst.tail.next
- }
-}
-
+ func (lst *List[T]) Push(v T) {
+ if lst.tail == nil {
+ lst.head = &element[T]{val: v}
+ lst.tail = lst.head
+ } else {
+ lst.tail.next = &element[T]{val: v}
+ lst.tail = lst.tail.next
+ }
+}
@@ -144,14 +135,13 @@ parameters in place. The type is List[T]
, not List
.
- func (lst *List[T]) GetAll() []T {
- var elems []T
- for e := lst.head; e != nil; e = e.next {
- elems = append(elems, e.val)
- }
- return elems
-}
-
+ func (lst *List[T]) GetAll() []T {
+ var elems []T
+ for e := lst.head; e != nil; e = e.next {
+ elems = append(elems, e.val)
+ }
+ return elems
+}
@@ -161,9 +151,8 @@ parameters in place. The type is List[T]
, not List
.
- func main() {
- var m = map[int]string{1: "2", 2: "4", 4: "8"}
-
+ func main() {
+ var m = map[int]string{1: "2", 2: "4", 4: "8"}
@@ -178,9 +167,7 @@ automatically.
-
- fmt.Println("keys:", MapKeys(m))
-
+ fmt.Println("keys:", MapKeys(m))
@@ -191,9 +178,7 @@ automatically.
-
- _ = MapKeys[int, string](m)
-
+ _ = MapKeys[int, string](m)
@@ -203,13 +188,12 @@ automatically.
- lst := List[int]{}
- lst.Push(10)
- lst.Push(13)
- lst.Push(23)
- fmt.Println("list:", lst.GetAll())
-}
-
+ lst := List[int]{}
+ lst.Push(10)
+ lst.Push(13)
+ lst.Push(23)
+ fmt.Println("list:", lst.GetAll())
+}
@@ -223,9 +207,9 @@ automatically.
- $ go run generics.go
-keys: [4 1 2]
-list: [10 13 23]
+ $ go run generics.go
+keys: [4 1 2]
+list: [10 13 23]
diff --git a/public/goroutines b/public/goroutines
index 957edc6..6b16ea9 100644
--- a/public/goroutines
+++ b/public/goroutines
@@ -42,8 +42,7 @@

- package main
-
+ package main
@@ -53,11 +52,10 @@
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -67,12 +65,11 @@
- func f(from string) {
- for i := 0; i < 3; i++ {
- fmt.Println(from, ":", i)
- }
-}
-
+ func f(from string) {
+ for i := 0; i < 3; i++ {
+ fmt.Println(from, ":", i)
+ }
+}
@@ -82,8 +79,7 @@
- func main() {
-
+ func main() {
@@ -96,9 +92,7 @@ synchronously.
-
- f("direct")
-
+ f("direct")
@@ -111,9 +105,7 @@ concurrently with the calling one.
-
- go f("goroutine")
-
+ go f("goroutine")
@@ -125,11 +117,9 @@ function call.
-
- go func(msg string) {
- fmt.Println(msg)
- }("going")
-
+ go func(msg string) {
+ fmt.Println(msg)
+ }("going")
@@ -142,11 +132,9 @@ separate goroutines now. Wait for them to finish
-
- time.Sleep(time.Second)
- fmt.Println("done")
-}
-
+ time.Sleep(time.Second)
+ fmt.Println("done")
+}
@@ -165,16 +153,15 @@ Go runtime.
-
-$ go run goroutines.go
-direct : 0
-direct : 1
-direct : 2
-goroutine : 0
-going
-goroutine : 1
-goroutine : 2
-done
+ $ go run goroutines.go
+direct : 0
+direct : 1
+direct : 2
+goroutine : 0
+going
+goroutine : 1
+goroutine : 2
+done
diff --git a/public/hello-world b/public/hello-world
index 6f28be4..83c5787 100644
--- a/public/hello-world
+++ b/public/hello-world
@@ -29,9 +29,7 @@ message. Here’s the full source code.

-
-package main
-
+ package main
@@ -41,8 +39,7 @@ message. Here’s the full source code.
- import "fmt"
-
+ import "fmt"
@@ -52,10 +49,9 @@ message. Here’s the full source code.
- func main() {
- fmt.Println("hello world")
-}
-
+ func main() {
+ fmt.Println("hello world")
+}
@@ -71,9 +67,8 @@ use go run
.
-
-$ go run hello-world.go
-hello world
+ $ go run hello-world.go
+hello world
@@ -85,10 +80,9 @@ binaries. We can do this using go build
.
-
-$ go build hello-world.go
-$ ls
-hello-world hello-world.go
+ $ go build hello-world.go
+$ ls
+hello-world hello-world.go
@@ -99,9 +93,8 @@ binaries. We can do this using go build
.
-
-$ ./hello-world
-hello world
+ $ ./hello-world
+hello world
diff --git a/public/http-client b/public/http-client
index 763290b..b693af7 100644
--- a/public/http-client
+++ b/public/http-client
@@ -35,9 +35,7 @@ HTTP requests.

-
-package main
-
+ package main
@@ -47,12 +45,11 @@ HTTP requests.
- import (
- "bufio"
- "fmt"
- "net/http"
-)
-
+ import (
+ "bufio"
+ "fmt"
+ "net/http"
+)
@@ -62,8 +59,7 @@ HTTP requests.
- func main() {
-
+ func main() {
@@ -78,13 +74,11 @@ settings.
-
- resp, err := http.Get("https://gobyexample.com")
- if err != nil {
- panic(err)
- }
- defer resp.Body.Close()
-
+ resp, err := http.Get("https://gobyexample.com")
+ if err != nil {
+ panic(err)
+ }
+ defer resp.Body.Close()
@@ -95,9 +89,7 @@ settings.
-
- fmt.Println("Response status:", resp.Status)
-
+ fmt.Println("Response status:", resp.Status)
@@ -108,12 +100,10 @@ settings.
-
- scanner := bufio.NewScanner(resp.Body)
- for i := 0; scanner.Scan() && i < 5; i++ {
- fmt.Println(scanner.Text())
- }
-
+ scanner := bufio.NewScanner(resp.Body)
+ for i := 0; scanner.Scan() && i < 5; i++ {
+ fmt.Println(scanner.Text())
+ }
@@ -123,11 +113,10 @@ settings.
- if err := scanner.Err(); err != nil {
- panic(err)
- }
-}
-
+ if err := scanner.Err(); err != nil {
+ panic(err)
+ }
+}
@@ -141,13 +130,13 @@ settings.
- $ go run http-clients.go
-Response status: 200 OK
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- <title>Go by Example</title>
+ $ go run http-clients.go
+Response status: 200 OK
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>Go by Example</title>
diff --git a/public/http-server b/public/http-server
index 70cdb54..e2ecdc6 100644
--- a/public/http-server
+++ b/public/http-server
@@ -33,9 +33,7 @@

-
-package main
-
+ package main
@@ -45,11 +43,10 @@
- import (
- "fmt"
- "net/http"
-)
-
+ import (
+ "fmt"
+ "net/http"
+)
@@ -64,9 +61,7 @@ on functions with the appropriate signature.
-
-func hello(w http.ResponseWriter, req *http.Request) {
-
+ func hello(w http.ResponseWriter, req *http.Request) {
@@ -81,10 +76,8 @@ HTTP response. Here our simple response is just
-
- fmt.Fprintf(w, "hello\n")
-}
-
+ fmt.Fprintf(w, "hello\n")
+}
@@ -94,8 +87,7 @@ HTTP response. Here our simple response is just
- func headers(w http.ResponseWriter, req *http.Request) {
-
+ func headers(w http.ResponseWriter, req *http.Request) {
@@ -108,14 +100,12 @@ headers and echoing them into the response body.
-
- for name, headers := range req.Header {
- for _, h := range headers {
- fmt.Fprintf(w, "%v: %v\n", name, h)
- }
- }
-}
-
+ for name, headers := range req.Header {
+ for _, h := range headers {
+ fmt.Fprintf(w, "%v: %v\n", name, h)
+ }
+ }
+}
@@ -125,8 +115,7 @@ headers and echoing them into the response body.
- func main() {
-
+ func main() {
@@ -140,10 +129,8 @@ takes a function as an argument.
-
- http.HandleFunc("/hello", hello)
- http.HandleFunc("/headers", headers)
-
+ http.HandleFunc("/hello", hello)
+ http.HandleFunc("/headers", headers)
@@ -156,10 +143,8 @@ router we’ve just set up.
-
- http.ListenAndServe(":8090", nil)
-}
-
+ http.ListenAndServe(":8090", nil)
+}
@@ -174,8 +159,7 @@ router we’ve just set up.
-
-$ go run http-servers.go &
+ $ go run http-servers.go &
@@ -186,9 +170,8 @@ router we’ve just set up.
-
-$ curl localhost:8090/hello
-hello
+ $ curl localhost:8090/hello
+hello
diff --git a/public/if-else b/public/if-else
index ec12be9..c394864 100644
--- a/public/if-else
+++ b/public/if-else
@@ -43,8 +43,7 @@ straight-forward.

- package main
-
+ package main
@@ -54,8 +53,7 @@ straight-forward.
- import "fmt"
-
+ import "fmt"
@@ -65,8 +63,7 @@ straight-forward.
- func main() {
-
+ func main() {
@@ -77,13 +74,11 @@ straight-forward.
-
- if 7%2 == 0 {
- fmt.Println("7 is even")
- } else {
- fmt.Println("7 is odd")
- }
-
+ if 7%2 == 0 {
+ fmt.Println("7 is even")
+ } else {
+ fmt.Println("7 is odd")
+ }
@@ -94,11 +89,9 @@ straight-forward.
-
- if 8%4 == 0 {
- fmt.Println("8 is divisible by 4")
- }
-
+ if 8%4 == 0 {
+ fmt.Println("8 is divisible by 4")
+ }
@@ -111,16 +104,14 @@ and all subsequent branches.
-
- if num := 9; num < 0 {
- fmt.Println(num, "is negative")
- } else if num < 10 {
- fmt.Println(num, "has 1 digit")
- } else {
- fmt.Println(num, "has multiple digits")
- }
-}
-
+ if num := 9; num < 0 {
+ fmt.Println(num, "is negative")
+ } else if num < 10 {
+ fmt.Println(num, "has 1 digit")
+ } else {
+ fmt.Println(num, "has multiple digits")
+ }
+}
@@ -146,10 +137,10 @@ in Go, but that the braces are required.
- $ go run if-else.go
-7 is odd
-8 is divisible by 4
-9 has 1 digit
+ $ go run if-else.go
+7 is odd
+8 is divisible by 4
+9 has 1 digit
diff --git a/public/interfaces b/public/interfaces
index 36cef1b..fd3b131 100644
--- a/public/interfaces
+++ b/public/interfaces
@@ -43,8 +43,7 @@ signatures.

- package main
-
+ package main
@@ -54,11 +53,10 @@ signatures.
- import (
- "fmt"
- "math"
-)
-
+ import (
+ "fmt"
+ "math"
+)
@@ -69,12 +67,10 @@ signatures.
-
-type geometry interface {
- area() float64
- perim() float64
-}
-
+ type geometry interface {
+ area() float64
+ perim() float64
+}
@@ -86,14 +82,12 @@ signatures.
-
-type rect struct {
- width, height float64
-}
-type circle struct {
- radius float64
-}
-
+ type rect struct {
+ width, height float64
+}
+type circle struct {
+ radius float64
+}
@@ -106,14 +100,12 @@ implement geometry
on rect
s.
-
-func (r rect) area() float64 {
- return r.width * r.height
-}
-func (r rect) perim() float64 {
- return 2*r.width + 2*r.height
-}
-
+ func (r rect) area() float64 {
+ return r.width * r.height
+}
+func (r rect) perim() float64 {
+ return 2*r.width + 2*r.height
+}
@@ -124,14 +116,12 @@ implement geometry
on rect
s.
-
-func (c circle) area() float64 {
- return math.Pi * c.radius * c.radius
-}
-func (c circle) perim() float64 {
- return 2 * math.Pi * c.radius
-}
-
+ func (c circle) area() float64 {
+ return math.Pi * c.radius * c.radius
+}
+func (c circle) perim() float64 {
+ return 2 * math.Pi * c.radius
+}
@@ -145,13 +135,11 @@ to work on any geometry
.
-
-func measure(g geometry) {
- fmt.Println(g)
- fmt.Println(g.area())
- fmt.Println(g.perim())
-}
-
+ func measure(g geometry) {
+ fmt.Println(g)
+ fmt.Println(g.area())
+ fmt.Println(g.perim())
+}
@@ -161,10 +149,9 @@ to work on any geometry
.
- func main() {
- r := rect{width: 3, height: 4}
- c := circle{radius: 5}
-
+ func main() {
+ r := rect{width: 3, height: 4}
+ c := circle{radius: 5}
@@ -178,11 +165,9 @@ these structs as arguments to measure
.
-
- measure(r)
- measure(c)
-}
-
+ measure(r)
+ measure(c)
+}
@@ -196,13 +181,13 @@ these structs as arguments to measure
.
- $ go run interfaces.go
-{3 4}
-12
-14
-{5}
-78.53981633974483
-31.41592653589793
+ $ go run interfaces.go
+{3 4}
+12
+14
+{5}
+78.53981633974483
+31.41592653589793
diff --git a/public/json b/public/json
index f1d7040..e33a3ef 100644
--- a/public/json
+++ b/public/json
@@ -44,8 +44,7 @@ data types.

- package main
-
+ package main
@@ -55,12 +54,11 @@ data types.
- import (
- "encoding/json"
- "fmt"
- "os"
-)
-
+ import (
+ "encoding/json"
+ "fmt"
+ "os"
+)
@@ -72,12 +70,10 @@ decoding of custom types below.
-
-type response1 struct {
- Page int
- Fruits []string
-}
-
+ type response1 struct {
+ Page int
+ Fruits []string
+}
@@ -89,12 +85,10 @@ Fields must start with capital letters to be exported.
-
-type response2 struct {
- Page int `json:"page"`
- Fruits []string `json:"fruits"`
-}
-
+ type response2 struct {
+ Page int `json:"page"`
+ Fruits []string `json:"fruits"`
+}
@@ -104,8 +98,7 @@ Fields must start with capital letters to be exported.
- func main() {
-
+ func main() {
@@ -118,10 +111,8 @@ values.
-
- bolB, _ := json.Marshal(true)
- fmt.Println(string(bolB))
-
+ bolB, _ := json.Marshal(true)
+ fmt.Println(string(bolB))
@@ -131,9 +122,8 @@ values.
- intB, _ := json.Marshal(1)
- fmt.Println(string(intB))
-
+ intB, _ := json.Marshal(1)
+ fmt.Println(string(intB))
@@ -143,9 +133,8 @@ values.
- fltB, _ := json.Marshal(2.34)
- fmt.Println(string(fltB))
-
+ fltB, _ := json.Marshal(2.34)
+ fmt.Println(string(fltB))
@@ -155,9 +144,8 @@ values.
- strB, _ := json.Marshal("gopher")
- fmt.Println(string(strB))
-
+ strB, _ := json.Marshal("gopher")
+ fmt.Println(string(strB))
@@ -169,11 +157,9 @@ to JSON arrays and objects as you’d expect.
-
- slcD := []string{"apple", "peach", "pear"}
- slcB, _ := json.Marshal(slcD)
- fmt.Println(string(slcB))
-
+ slcD := []string{"apple", "peach", "pear"}
+ slcB, _ := json.Marshal(slcD)
+ fmt.Println(string(slcB))
@@ -183,10 +169,9 @@ to JSON arrays and objects as you’d expect.
- mapD := map[string]int{"apple": 5, "lettuce": 7}
- mapB, _ := json.Marshal(mapD)
- fmt.Println(string(mapB))
-
+ mapD := map[string]int{"apple": 5, "lettuce": 7}
+ mapB, _ := json.Marshal(mapD)
+ fmt.Println(string(mapB))
@@ -200,13 +185,11 @@ use those names as the JSON keys.
-
- res1D := &response1{
- Page: 1,
- Fruits: []string{"apple", "peach", "pear"}}
- res1B, _ := json.Marshal(res1D)
- fmt.Println(string(res1B))
-
+ res1D := &response1{
+ Page: 1,
+ Fruits: []string{"apple", "peach", "pear"}}
+ res1B, _ := json.Marshal(res1D)
+ fmt.Println(string(res1B))
@@ -220,13 +203,11 @@ of such tags.
-
- res2D := &response2{
- Page: 1,
- Fruits: []string{"apple", "peach", "pear"}}
- res2B, _ := json.Marshal(res2D)
- fmt.Println(string(res2B))
-
+ res2D := &response2{
+ Page: 1,
+ Fruits: []string{"apple", "peach", "pear"}}
+ res2B, _ := json.Marshal(res2D)
+ fmt.Println(string(res2B))
@@ -239,9 +220,7 @@ structure.
-
- byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
-
+ byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
@@ -255,9 +234,7 @@ to arbitrary data types.
-
- var dat map[string]interface{}
-
+ var dat map[string]interface{}
@@ -269,12 +246,10 @@ associated errors.
-
- if err := json.Unmarshal(byt, &dat); err != nil {
- panic(err)
- }
- fmt.Println(dat)
-
+ if err := json.Unmarshal(byt, &dat); err != nil {
+ panic(err)
+ }
+ fmt.Println(dat)
@@ -288,10 +263,8 @@ the expected float64
type.
-
- num := dat["num"].(float64)
- fmt.Println(num)
-
+ num := dat["num"].(float64)
+ fmt.Println(num)
@@ -303,11 +276,9 @@ conversions.
-
- strs := dat["strs"].([]interface{})
- str1 := strs[0].(string)
- fmt.Println(str1)
-
+ strs := dat["strs"].([]interface{})
+ str1 := strs[0].(string)
+ fmt.Println(str1)
@@ -322,13 +293,11 @@ data.
-
- str := `{"page": 1, "fruits": ["apple", "peach"]}`
- res := response2{}
- json.Unmarshal([]byte(str), &res)
- fmt.Println(res)
- fmt.Println(res.Fruits[0])
-
+ str := `{"page": 1, "fruits": ["apple", "peach"]}`
+ res := response2{}
+ json.Unmarshal([]byte(str), &res)
+ fmt.Println(res)
+ fmt.Println(res.Fruits[0])
@@ -343,12 +312,10 @@ stream JSON encodings directly to os.Writer
s like
-
- enc := json.NewEncoder(os.Stdout)
- d := map[string]int{"apple": 5, "lettuce": 7}
- enc.Encode(d)
-}
-
+ enc := json.NewEncoder(os.Stdout)
+ d := map[string]int{"apple": 5, "lettuce": 7}
+ enc.Encode(d)
+}
@@ -362,21 +329,21 @@ stream JSON encodings directly to os.Writer
s like
- $ go run json.go
-true
-1
-2.34
-"gopher"
-["apple","peach","pear"]
-{"apple":5,"lettuce":7}
-{"Page":1,"Fruits":["apple","peach","pear"]}
-{"page":1,"fruits":["apple","peach","pear"]}
-map[num:6.13 strs:[a b]]
-6.13
-a
-{1 [apple peach]}
-apple
-{"apple":5,"lettuce":7}
+ $ go run json.go
+true
+1
+2.34
+"gopher"
+["apple","peach","pear"]
+{"apple":5,"lettuce":7}
+{"Page":1,"Fruits":["apple","peach","pear"]}
+{"page":1,"fruits":["apple","peach","pear"]}
+map[num:6.13 strs:[a b]]
+6.13
+a
+{1 [apple peach]}
+apple
+{"apple":5,"lettuce":7}
diff --git a/public/line-filters b/public/line-filters
index 3fcb704..4dc0a87 100644
--- a/public/line-filters
+++ b/public/line-filters
@@ -48,9 +48,7 @@ pattern to write your own Go line filters.

-
-package main
-
+ package main
@@ -60,13 +58,12 @@ pattern to write your own Go line filters.
- import (
- "bufio"
- "fmt"
- "os"
- "strings"
-)
-
+ import (
+ "bufio"
+ "fmt"
+ "os"
+ "strings"
+)
@@ -76,8 +73,7 @@ pattern to write your own Go line filters.
- func main() {
-
+ func main() {
@@ -91,9 +87,7 @@ the next line in the default scanner.
-
- scanner := bufio.NewScanner(os.Stdin)
-
+ scanner := bufio.NewScanner(os.Stdin)
@@ -105,8 +99,7 @@ from the input.
- for scanner.Scan() {
-
+ for scanner.Scan() {
@@ -116,8 +109,7 @@ from the input.
- ucl := strings.ToUpper(scanner.Text())
-
+ ucl := strings.ToUpper(scanner.Text())
@@ -128,10 +120,8 @@ from the input.
-
- fmt.Println(ucl)
- }
-
+ fmt.Println(ucl)
+ }
@@ -143,13 +133,11 @@ expected and not reported by Scan
as an error.
-
- if err := scanner.Err(); err != nil {
- fmt.Fprintln(os.Stderr, "error:", err)
- os.Exit(1)
- }
-}
-
+ if err := scanner.Err(); err != nil {
+ fmt.Fprintln(os.Stderr, "error:", err)
+ os.Exit(1)
+ }
+}
@@ -165,9 +153,8 @@ lowercase lines.
-
-$ echo 'hello' > /tmp/lines
-$ echo 'filter' >> /tmp/lines
+ $ echo 'hello' > /tmp/lines
+$ echo 'filter' >> /tmp/lines
@@ -178,10 +165,9 @@ lowercase lines.
-
-$ cat /tmp/lines | go run line-filters.go
-HELLO
-FILTER
+ $ cat /tmp/lines | go run line-filters.go
+HELLO
+FILTER
diff --git a/public/maps b/public/maps
index b3e0fe8..94427d5 100644
--- a/public/maps
+++ b/public/maps
@@ -43,8 +43,7 @@

- package main
-
+ package main
@@ -54,8 +53,7 @@
- import "fmt"
-
+ import "fmt"
@@ -65,8 +63,7 @@
- func main() {
-
+ func main() {
@@ -78,9 +75,7 @@
-
- m := make(map[string]int)
-
+ m := make(map[string]int)
@@ -92,10 +87,8 @@ syntax.
-
- m["k1"] = 7
- m["k2"] = 13
-
+ m["k1"] = 7
+ m["k2"] = 13
@@ -107,9 +100,7 @@ its key/value pairs.
-
- fmt.Println("map:", m)
-
+ fmt.Println("map:", m)
@@ -120,10 +111,8 @@ its key/value pairs.
-
- v1 := m["k1"]
- fmt.Println("v1:", v1)
-
+ v1 := m["k1"]
+ fmt.Println("v1:", v1)
@@ -136,10 +125,8 @@ value type is returned.
-
- v3 := m["k3"]
- fmt.Println("v3:", v3)
-
+ v3 := m["k3"]
+ fmt.Println("v3:", v3)
@@ -151,9 +138,7 @@ pairs when called on a map.
-
- fmt.Println("len:", len(m))
-
+ fmt.Println("len:", len(m))
@@ -165,10 +150,8 @@ a map.
-
- delete(m, "k2")
- fmt.Println("map:", m)
-
+ delete(m, "k2")
+ fmt.Println("map:", m)
@@ -180,10 +163,8 @@ the clear
builtin.
-
- clear(m)
- fmt.Println("map:", m)
-
+ clear(m)
+ fmt.Println("map:", m)
@@ -200,10 +181,8 @@ itself, so we ignored it with the blank identifier
-
- _, prs := m["k2"]
- fmt.Println("prs:", prs)
-
+ _, prs := m["k2"]
+ fmt.Println("prs:", prs)
@@ -215,11 +194,9 @@ the same line with this syntax.
-
- n := map[string]int{"foo": 1, "bar": 2}
- fmt.Println("map:", n)
-}
-
+ n := map[string]int{"foo": 1, "bar": 2}
+ fmt.Println("map:", n)
+}
@@ -235,16 +212,15 @@ printed with fmt.Println
.
-
-$ go run maps.go
-map: map[k1:7 k2:13]
-v1: 7
-v3: 0
-len: 2
-map: map[k1:7]
-map: map[]
-prs: false
-map: map[bar:2 foo:1]
+ $ go run maps.go
+map: map[k1:7 k2:13]
+v1: 7
+v3: 0
+len: 2
+map: map[k1:7]
+map: map[]
+prs: false
+map: map[bar:2 foo:1]
diff --git a/public/methods b/public/methods
index b04b063..70d36d0 100644
--- a/public/methods
+++ b/public/methods
@@ -42,8 +42,7 @@

- package main
-
+ package main
@@ -53,8 +52,7 @@
- import "fmt"
-
+ import "fmt"
@@ -64,10 +62,9 @@
- type rect struct {
- width, height int
-}
-
+ type rect struct {
+ width, height int
+}
@@ -78,11 +75,9 @@
-
-func (r *rect) area() int {
- return r.width * r.height
-}
-
+ func (r *rect) area() int {
+ return r.width * r.height
+}
@@ -94,11 +89,9 @@ receiver types. Here’s an example of a value receiver.
-
-func (r rect) perim() int {
- return 2*r.width + 2*r.height
-}
-
+ func (r rect) perim() int {
+ return 2*r.width + 2*r.height
+}
@@ -108,9 +101,8 @@ receiver types. Here’s an example of a value receiver.
- func main() {
- r := rect{width: 10, height: 5}
-
+ func main() {
+ r := rect{width: 10, height: 5}
@@ -121,10 +113,8 @@ receiver types. Here’s an example of a value receiver.
-
- fmt.Println("area: ", r.area())
- fmt.Println("perim:", r.perim())
-
+ fmt.Println("area: ", r.area())
+ fmt.Println("perim:", r.perim())
@@ -139,12 +129,10 @@ receiving struct.
-
- rp := &r
- fmt.Println("area: ", rp.area())
- fmt.Println("perim:", rp.perim())
-}
-
+ rp := &r
+ fmt.Println("area: ", rp.area())
+ fmt.Println("perim:", rp.perim())
+}
@@ -158,11 +146,11 @@ receiving struct.
- $ go run methods.go
-area: 50
-perim: 30
-area: 50
-perim: 30
+ $ go run methods.go
+area: 50
+perim: 30
+area: 50
+perim: 30
diff --git a/public/multiple-return-values b/public/multiple-return-values
index 9fbc33d..7f6d6d4 100644
--- a/public/multiple-return-values
+++ b/public/multiple-return-values
@@ -44,8 +44,7 @@ to return both result and error values from a function.

- package main
-
+ package main
@@ -55,8 +54,7 @@ to return both result and error values from a function.
- import "fmt"
-
+ import "fmt"
@@ -68,11 +66,9 @@ the function returns 2 int
s.
-
-func vals() (int, int) {
- return 3, 7
-}
-
+ func vals() (int, int) {
+ return 3, 7
+}
@@ -82,8 +78,7 @@ the function returns 2 int
s.
- func main() {
-
+ func main() {
@@ -95,11 +90,9 @@ call with multiple assignment.
-
- a, b := vals()
- fmt.Println(a)
- fmt.Println(b)
-
+ a, b := vals()
+ fmt.Println(a)
+ fmt.Println(b)
@@ -111,11 +104,9 @@ use the blank identifier _
.
-
- _, c := vals()
- fmt.Println(c)
-}
-
+ _, c := vals()
+ fmt.Println(c)
+}
@@ -129,10 +120,10 @@ use the blank identifier _
.
- $ go run multiple-return-values.go
-3
-7
-7
+ $ go run multiple-return-values.go
+3
+7
+7
diff --git a/public/mutexes b/public/mutexes
index 9dc784d..b888856 100644
--- a/public/mutexes
+++ b/public/mutexes
@@ -45,8 +45,7 @@ to safely access data across multiple goroutines.

- package main
-
+ package main
@@ -56,11 +55,10 @@ to safely access data across multiple goroutines.
- import (
- "fmt"
- "sync"
-)
-
+ import (
+ "fmt"
+ "sync"
+)
@@ -76,12 +74,10 @@ pointer.
-
-type Container struct {
- mu sync.Mutex
- counters map[string]int
-}
-
+ type Container struct {
+ mu sync.Mutex
+ counters map[string]int
+}
@@ -94,8 +90,7 @@ statement.
- func (c *Container) inc(name string) {
-
+ func (c *Container) inc(name string) {
@@ -105,11 +100,10 @@ statement.
- c.mu.Lock()
- defer c.mu.Unlock()
- c.counters[name]++
-}
-
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.counters[name]++
+}
@@ -121,9 +115,8 @@ initialization is required here.
- func main() {
- c := Container{
-
+ func main() {
+ c := Container{
@@ -133,9 +126,8 @@ initialization is required here.
- counters: map[string]int{"a": 0, "b": 0},
- }
-
+ counters: map[string]int{"a": 0, "b": 0},
+ }
@@ -145,8 +137,7 @@ initialization is required here.
- var wg sync.WaitGroup
-
+ var wg sync.WaitGroup
@@ -158,14 +149,12 @@ in a loop.
-
- doIncrement := func(name string, n int) {
- for i := 0; i < n; i++ {
- c.inc(name)
- }
- wg.Done()
- }
-
+ doIncrement := func(name string, n int) {
+ for i := 0; i < n; i++ {
+ c.inc(name)
+ }
+ wg.Done()
+ }
@@ -178,12 +167,10 @@ and two of them access the same counter.
-
- wg.Add(3)
- go doIncrement("a", 10000)
- go doIncrement("a", 10000)
- go doIncrement("b", 10000)
-
+ wg.Add(3)
+ go doIncrement("a", 10000)
+ go doIncrement("a", 10000)
+ go doIncrement("b", 10000)
@@ -194,11 +181,9 @@ and two of them access the same counter.
-
- wg.Wait()
- fmt.Println(c.counters)
-}
-
+ wg.Wait()
+ fmt.Println(c.counters)
+}
@@ -214,9 +199,8 @@ updated as expected.
-
-$ go run mutexes.go
-map[a:20000 b:10000]
+ $ go run mutexes.go
+map[a:20000 b:10000]
diff --git a/public/non-blocking-channel-operations b/public/non-blocking-channel-operations
index 08d4bd6..4e70d05 100644
--- a/public/non-blocking-channel-operations
+++ b/public/non-blocking-channel-operations
@@ -45,8 +45,7 @@ non-blocking multi-way select
s.

- package main
-
+ package main
@@ -56,8 +55,7 @@ non-blocking multi-way select
s.
- import "fmt"
-
+ import "fmt"
@@ -67,10 +65,9 @@ non-blocking multi-way select
s.
- func main() {
- messages := make(chan string)
- signals := make(chan bool)
-
+ func main() {
+ messages := make(chan string)
+ signals := make(chan bool)
@@ -84,14 +81,12 @@ it will immediately take the default
case.
-
- select {
- case msg := <-messages:
- fmt.Println("received message", msg)
- default:
- fmt.Println("no message received")
- }
-
+ select {
+ case msg := <-messages:
+ fmt.Println("received message", msg)
+ default:
+ fmt.Println("no message received")
+ }
@@ -105,15 +100,13 @@ Therefore the default
case is selected.
-
- msg := "hi"
- select {
- case messages <- msg:
- fmt.Println("sent message", msg)
- default:
- fmt.Println("no message sent")
- }
-
+ msg := "hi"
+ select {
+ case messages <- msg:
+ fmt.Println("sent message", msg)
+ default:
+ fmt.Println("no message sent")
+ }
@@ -127,17 +120,15 @@ on both messages
and signals
.
-
- select {
- case msg := <-messages:
- fmt.Println("received message", msg)
- case sig := <-signals:
- fmt.Println("received signal", sig)
- default:
- fmt.Println("no activity")
- }
-}
-
+ select {
+ case msg := <-messages:
+ fmt.Println("received message", msg)
+ case sig := <-signals:
+ fmt.Println("received signal", sig)
+ default:
+ fmt.Println("no activity")
+ }
+}
@@ -151,10 +142,10 @@ on both messages
and signals
.
- $ go run non-blocking-channel-operations.go
-no message received
-no message sent
-no activity
+ $ go run non-blocking-channel-operations.go
+no message received
+no message sent
+no activity
diff --git a/public/number-parsing b/public/number-parsing
index af3d1d4..9bebcd3 100644
--- a/public/number-parsing
+++ b/public/number-parsing
@@ -43,8 +43,7 @@ in many programs; here’s how to do it in Go.

- package main
-
+ package main
@@ -56,12 +55,10 @@ parsing.
-
-import (
- "fmt"
- "strconv"
-)
-
+ import (
+ "fmt"
+ "strconv"
+)
@@ -71,8 +68,7 @@ parsing.
- func main() {
-
+ func main() {
@@ -84,10 +80,8 @@ precision to parse.
-
- f, _ := strconv.ParseFloat("1.234", 64)
- fmt.Println(f)
-
+ f, _ := strconv.ParseFloat("1.234", 64)
+ fmt.Println(f)
@@ -100,10 +94,8 @@ bits.
-
- i, _ := strconv.ParseInt("123", 0, 64)
- fmt.Println(i)
-
+ i, _ := strconv.ParseInt("123", 0, 64)
+ fmt.Println(i)
@@ -114,10 +106,8 @@ bits.
-
- d, _ := strconv.ParseInt("0x1c8", 0, 64)
- fmt.Println(d)
-
+ d, _ := strconv.ParseInt("0x1c8", 0, 64)
+ fmt.Println(d)
@@ -128,10 +118,8 @@ bits.
-
- u, _ := strconv.ParseUint("789", 0, 64)
- fmt.Println(u)
-
+ u, _ := strconv.ParseUint("789", 0, 64)
+ fmt.Println(u)
@@ -143,10 +131,8 @@ bits.
-
- k, _ := strconv.Atoi("135")
- fmt.Println(k)
-
+ k, _ := strconv.Atoi("135")
+ fmt.Println(k)
@@ -157,11 +143,9 @@ bits.
-
- _, e := strconv.Atoi("wat")
- fmt.Println(e)
-}
-
+ _, e := strconv.Atoi("wat")
+ fmt.Println(e)
+}
@@ -175,13 +159,13 @@ bits.
- $ go run number-parsing.go
-1.234
-123
-456
-789
-135
-strconv.ParseInt: parsing "wat": invalid syntax
+ $ go run number-parsing.go
+1.234
+123
+456
+789
+135
+strconv.ParseInt: parsing "wat": invalid syntax
diff --git a/public/panic b/public/panic
index a93770c..08636d8 100644
--- a/public/panic
+++ b/public/panic
@@ -45,8 +45,7 @@ aren’t prepared to handle gracefully.

- package main
-
+ package main
@@ -56,8 +55,7 @@ aren’t prepared to handle gracefully.
- import "os"
-
+ import "os"
@@ -67,8 +65,7 @@ aren’t prepared to handle gracefully.
- func main() {
-
+ func main() {
@@ -81,9 +78,7 @@ site designed to panic.
-
- panic("a problem")
-
+ panic("a problem")
@@ -97,13 +92,11 @@ returns an error value that we don’t know how to
-
- _, err := os.Create("/tmp/file")
- if err != nil {
- panic(err)
- }
-}
-
+ _, err := os.Create("/tmp/file")
+ if err != nil {
+ panic(err)
+ }
+}
@@ -134,9 +127,8 @@ the first panic out.
-
-$ go run panic.go
-panic: a problem
+ $ go run panic.go
+panic: a problem
@@ -146,11 +138,11 @@ the first panic out.
- goroutine 1 [running]:
-main.main()
- /.../panic.go:12 +0x47
-...
-exit status 2
+ goroutine 1 [running]:
+main.main()
+ /.../panic.go:12 +0x47
+...
+exit status 2
diff --git a/public/pointers b/public/pointers
index b57507a..cbb64a8 100644
--- a/public/pointers
+++ b/public/pointers
@@ -44,8 +44,7 @@ within your program.

- package main
-
+ package main
@@ -55,8 +54,7 @@ within your program.
- import "fmt"
-
+ import "fmt"
@@ -71,11 +69,9 @@ from the one in the calling function.
-
-func zeroval(ival int) {
- ival = 0
-}
-
+ func zeroval(ival int) {
+ ival = 0
+}
@@ -91,11 +87,9 @@ value at the referenced address.
-
-func zeroptr(iptr *int) {
- *iptr = 0
-}
-
+ func zeroptr(iptr *int) {
+ *iptr = 0
+}
@@ -105,10 +99,9 @@ value at the referenced address.
- func main() {
- i := 1
- fmt.Println("initial:", i)
-
+ func main() {
+ i := 1
+ fmt.Println("initial:", i)
@@ -118,9 +111,8 @@ value at the referenced address.
- zeroval(i)
- fmt.Println("zeroval:", i)
-
+ zeroval(i)
+ fmt.Println("zeroval:", i)
@@ -132,10 +124,8 @@ i.e. a pointer to i
.
-
- zeroptr(&i)
- fmt.Println("zeroptr:", i)
-
+ zeroptr(&i)
+ fmt.Println("zeroptr:", i)
@@ -146,10 +136,8 @@ i.e. a pointer to i
.
-
- fmt.Println("pointer:", &i)
-}
-
+ fmt.Println("pointer:", &i)
+}
@@ -166,12 +154,11 @@ the memory address for that variable.
-
-$ go run pointers.go
-initial: 1
-zeroval: 1
-zeroptr: 0
-pointer: 0x42131100
+ $ go run pointers.go
+initial: 1
+zeroval: 1
+zeroptr: 0
+pointer: 0x42131100
diff --git a/public/random-numbers b/public/random-numbers
index c1571e2..5b0a95f 100644
--- a/public/random-numbers
+++ b/public/random-numbers
@@ -44,8 +44,7 @@ generation.

- package main
-
+ package main
@@ -55,12 +54,11 @@ generation.
- import (
- "fmt"
- "math/rand"
- "time"
-)
-
+ import (
+ "fmt"
+ "math/rand"
+ "time"
+)
@@ -70,8 +68,7 @@ generation.
- func main() {
-
+ func main() {
@@ -83,11 +80,9 @@ generation.
-
- fmt.Print(rand.Intn(100), ",")
- fmt.Print(rand.Intn(100))
- fmt.Println()
-
+ fmt.Print(rand.Intn(100), ",")
+ fmt.Print(rand.Intn(100))
+ fmt.Println()
@@ -99,9 +94,7 @@ generation.
-
- fmt.Println(rand.Float64())
-
+ fmt.Println(rand.Float64())
@@ -113,11 +106,9 @@ other ranges, for example 5.0 <= f' < 10.0
.
-
- fmt.Print((rand.Float64()*5)+5, ",")
- fmt.Print((rand.Float64() * 5) + 5)
- fmt.Println()
-
+ fmt.Print((rand.Float64()*5)+5, ",")
+ fmt.Print((rand.Float64() * 5) + 5)
+ fmt.Println()
@@ -132,10 +123,8 @@ intend to be secret; use crypto/rand
for those.
-
- s1 := rand.NewSource(time.Now().UnixNano())
- r1 := rand.New(s1)
-
+ s1 := rand.NewSource(time.Now().UnixNano())
+ r1 := rand.New(s1)
@@ -147,11 +136,9 @@ functions on the rand
package.
-
- fmt.Print(r1.Intn(100), ",")
- fmt.Print(r1.Intn(100))
- fmt.Println()
-
+ fmt.Print(r1.Intn(100), ",")
+ fmt.Print(r1.Intn(100))
+ fmt.Println()
@@ -163,18 +150,16 @@ produces the same sequence of random numbers.
-
- s2 := rand.NewSource(42)
- r2 := rand.New(s2)
- fmt.Print(r2.Intn(100), ",")
- fmt.Print(r2.Intn(100))
- fmt.Println()
- s3 := rand.NewSource(42)
- r3 := rand.New(s3)
- fmt.Print(r3.Intn(100), ",")
- fmt.Print(r3.Intn(100))
-}
-
+ s2 := rand.NewSource(42)
+ r2 := rand.New(s2)
+ fmt.Print(r2.Intn(100), ",")
+ fmt.Print(r2.Intn(100))
+ fmt.Println()
+ s3 := rand.NewSource(42)
+ r3 := rand.New(s3)
+ fmt.Print(r3.Intn(100), ",")
+ fmt.Print(r3.Intn(100))
+}
@@ -193,14 +178,13 @@ playground is implemented.
-
-$ go run random-numbers.go
-81,87
-0.6645600532184904
-7.123187485356329,8.434115364335547
-0,28
-5,87
-5,87
+ $ go run random-numbers.go
+81,87
+0.6645600532184904
+7.123187485356329,8.434115364335547
+0,28
+5,87
+5,87
diff --git a/public/range b/public/range
index 5259ac7..3c83d60 100644
--- a/public/range
+++ b/public/range
@@ -44,8 +44,7 @@ of the data structures we’ve already learned.

- package main
-
+ package main
@@ -55,8 +54,7 @@ of the data structures we’ve already learned.
- import "fmt"
-
+ import "fmt"
@@ -66,8 +64,7 @@ of the data structures we’ve already learned.
- func main() {
-
+ func main() {
@@ -79,14 +76,12 @@ Arrays work like this too.
-
- nums := []int{2, 3, 4}
- sum := 0
- for _, num := range nums {
- sum += num
- }
- fmt.Println("sum:", sum)
-
+ nums := []int{2, 3, 4}
+ sum := 0
+ for _, num := range nums {
+ sum += num
+ }
+ fmt.Println("sum:", sum)
@@ -101,13 +96,11 @@ the indexes though.
-
- for i, num := range nums {
- if num == 3 {
- fmt.Println("index:", i)
- }
- }
-
+ for i, num := range nums {
+ if num == 3 {
+ fmt.Println("index:", i)
+ }
+ }
@@ -118,12 +111,10 @@ the indexes though.
-
- kvs := map[string]string{"a": "apple", "b": "banana"}
- for k, v := range kvs {
- fmt.Printf("%s -> %s\n", k, v)
- }
-
+ kvs := map[string]string{"a": "apple", "b": "banana"}
+ for k, v := range kvs {
+ fmt.Printf("%s -> %s\n", k, v)
+ }
@@ -134,11 +125,9 @@ the indexes though.
-
- for k := range kvs {
- fmt.Println("key:", k)
- }
-
+ for k := range kvs {
+ fmt.Println("key:", k)
+ }
@@ -153,12 +142,10 @@ details.
-
- for i, c := range "go" {
- fmt.Println(i, c)
- }
-}
-
+ for i, c := range "go" {
+ fmt.Println(i, c)
+ }
+}
@@ -172,15 +159,15 @@ details.
- $ go run range.go
-sum: 9
-index: 1
-a -> apple
-b -> banana
-key: a
-key: b
-0 103
-1 111
+ $ go run range.go
+sum: 9
+index: 1
+a -> apple
+b -> banana
+key: a
+key: b
+0 103
+1 111
diff --git a/public/range-over-channels b/public/range-over-channels
index bc4b71e..f460060 100644
--- a/public/range-over-channels
+++ b/public/range-over-channels
@@ -45,8 +45,7 @@ values received from a channel.

- package main
-
+ package main
@@ -56,8 +55,7 @@ values received from a channel.
- import "fmt"
-
+ import "fmt"
@@ -67,8 +65,7 @@ values received from a channel.
- func main() {
-
+ func main() {
@@ -79,12 +76,10 @@ values received from a channel.
-
- queue := make(chan string, 2)
- queue <- "one"
- queue <- "two"
- close(queue)
-
+ queue := make(chan string, 2)
+ queue <- "one"
+ queue <- "two"
+ close(queue)
@@ -98,12 +93,10 @@ receiving the 2 elements.
-
- for elem := range queue {
- fmt.Println(elem)
- }
-}
-
+ for elem := range queue {
+ fmt.Println(elem)
+ }
+}
@@ -117,9 +110,9 @@ receiving the 2 elements.
- $ go run range-over-channels.go
-one
-two
+ $ go run range-over-channels.go
+one
+two
diff --git a/public/rate-limiting b/public/rate-limiting
index ceb2a71..4ce31db 100644
--- a/public/rate-limiting
+++ b/public/rate-limiting
@@ -46,8 +46,7 @@ channels, and tickers.

- package main
-
+ package main
@@ -57,11 +56,10 @@ channels, and tickers.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -71,8 +69,7 @@ channels, and tickers.
- func main() {
-
+ func main() {
@@ -86,13 +83,11 @@ same name.
-
- requests := make(chan int, 5)
- for i := 1; i <= 5; i++ {
- requests <- i
- }
- close(requests)
-
+ requests := make(chan int, 5)
+ for i := 1; i <= 5; i++ {
+ requests <- i
+ }
+ close(requests)
@@ -105,9 +100,7 @@ our rate limiting scheme.
-
- limiter := time.Tick(200 * time.Millisecond)
-
+ limiter := time.Tick(200 * time.Millisecond)
@@ -120,12 +113,10 @@ before serving each request, we limit ourselves to
-
- for req := range requests {
- <-limiter
- fmt.Println("request", req, time.Now())
- }
-
+ for req := range requests {
+ <-limiter
+ fmt.Println("request", req, time.Now())
+ }
@@ -140,9 +131,7 @@ channel will allow bursts of up to 3 events.
-
- burstyLimiter := make(chan time.Time, 3)
-
+ burstyLimiter := make(chan time.Time, 3)
@@ -153,11 +142,9 @@ channel will allow bursts of up to 3 events.
-
- for i := 0; i < 3; i++ {
- burstyLimiter <- time.Now()
- }
-
+ for i := 0; i < 3; i++ {
+ burstyLimiter <- time.Now()
+ }
@@ -169,13 +156,11 @@ value to burstyLimiter
, up to its limit of 3.
-
- go func() {
- for t := range time.Tick(200 * time.Millisecond) {
- burstyLimiter <- t
- }
- }()
-
+ go func() {
+ for t := range time.Tick(200 * time.Millisecond) {
+ burstyLimiter <- t
+ }
+ }()
@@ -188,18 +173,16 @@ of burstyLimiter
.
-
- burstyRequests := make(chan int, 5)
- for i := 1; i <= 5; i++ {
- burstyRequests <- i
- }
- close(burstyRequests)
- for req := range burstyRequests {
- <-burstyLimiter
- fmt.Println("request", req, time.Now())
- }
-}
-
+ burstyRequests := make(chan int, 5)
+ for i := 1; i <= 5; i++ {
+ burstyRequests <- i
+ }
+ close(burstyRequests)
+ for req := range burstyRequests {
+ <-burstyLimiter
+ fmt.Println("request", req, time.Now())
+ }
+}
@@ -215,13 +198,12 @@ handled once every ~200 milliseconds as desired.
-
-$ go run rate-limiting.go
-request 1 2012-10-19 00:38:18.687438 +0000 UTC
-request 2 2012-10-19 00:38:18.887471 +0000 UTC
-request 3 2012-10-19 00:38:19.087238 +0000 UTC
-request 4 2012-10-19 00:38:19.287338 +0000 UTC
-request 5 2012-10-19 00:38:19.487331 +0000 UTC
+ $ go run rate-limiting.go
+request 1 2012-10-19 00:38:18.687438 +0000 UTC
+request 2 2012-10-19 00:38:18.887471 +0000 UTC
+request 3 2012-10-19 00:38:19.087238 +0000 UTC
+request 4 2012-10-19 00:38:19.287338 +0000 UTC
+request 5 2012-10-19 00:38:19.487331 +0000 UTC
@@ -234,12 +216,11 @@ then serve the remaining 2 with ~200ms delays each.
-
-request 1 2012-10-19 00:38:20.487578 +0000 UTC
-request 2 2012-10-19 00:38:20.487645 +0000 UTC
-request 3 2012-10-19 00:38:20.487676 +0000 UTC
-request 4 2012-10-19 00:38:20.687483 +0000 UTC
-request 5 2012-10-19 00:38:20.887542 +0000 UTC
+ request 1 2012-10-19 00:38:20.487578 +0000 UTC
+request 2 2012-10-19 00:38:20.487645 +0000 UTC
+request 3 2012-10-19 00:38:20.487676 +0000 UTC
+request 4 2012-10-19 00:38:20.687483 +0000 UTC
+request 5 2012-10-19 00:38:20.887542 +0000 UTC
diff --git a/public/reading-files b/public/reading-files
index 58fc5bc..fceb4bd 100644
--- a/public/reading-files
+++ b/public/reading-files
@@ -44,8 +44,7 @@ reading files.

- package main
-
+ package main
@@ -55,13 +54,12 @@ reading files.
- import (
- "bufio"
- "fmt"
- "io"
- "os"
-)
-
+ import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+)
@@ -73,13 +71,11 @@ This helper will streamline our error checks below.
-
-func check(e error) {
- if e != nil {
- panic(e)
- }
-}
-
+ func check(e error) {
+ if e != nil {
+ panic(e)
+ }
+}
@@ -89,8 +85,7 @@ This helper will streamline our error checks below.
- func main() {
-
+ func main() {
@@ -102,11 +97,9 @@ slurping a file’s entire contents into memory.
-
- dat, err := os.ReadFile("/tmp/dat")
- check(err)
- fmt.Print(string(dat))
-
+ dat, err := os.ReadFile("/tmp/dat")
+ check(err)
+ fmt.Print(string(dat))
@@ -119,10 +112,8 @@ by Open
ing a file to obtain an os.File
value.
-
- f, err := os.Open("/tmp/dat")
- check(err)
-
+ f, err := os.Open("/tmp/dat")
+ check(err)
@@ -135,12 +126,10 @@ actually were read.
-
- b1 := make([]byte, 5)
- n1, err := f.Read(b1)
- check(err)
- fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
-
+ b1 := make([]byte, 5)
+ n1, err := f.Read(b1)
+ check(err)
+ fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
@@ -152,15 +141,13 @@ and Read
from there.
-
- o2, err := f.Seek(6, 0)
- check(err)
- b2 := make([]byte, 2)
- n2, err := f.Read(b2)
- check(err)
- fmt.Printf("%d bytes @ %d: ", n2, o2)
- fmt.Printf("%v\n", string(b2[:n2]))
-
+ o2, err := f.Seek(6, 0)
+ check(err)
+ b2 := make([]byte, 2)
+ n2, err := f.Read(b2)
+ check(err)
+ fmt.Printf("%d bytes @ %d: ", n2, o2)
+ fmt.Printf("%v\n", string(b2[:n2]))
@@ -174,14 +161,12 @@ implemented with ReadAtLeast
.
-
- o3, err := f.Seek(6, 0)
- check(err)
- b3 := make([]byte, 2)
- n3, err := io.ReadAtLeast(f, b3, 2)
- check(err)
- fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
-
+ o3, err := f.Seek(6, 0)
+ check(err)
+ b3 := make([]byte, 2)
+ n3, err := io.ReadAtLeast(f, b3, 2)
+ check(err)
+ fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
@@ -193,10 +178,8 @@ accomplishes this.
-
- _, err = f.Seek(0, 0)
- check(err)
-
+ _, err = f.Seek(0, 0)
+ check(err)
@@ -210,12 +193,10 @@ reading methods it provides.
-
- r4 := bufio.NewReader(f)
- b4, err := r4.Peek(5)
- check(err)
- fmt.Printf("5 bytes: %s\n", string(b4))
-
+ r4 := bufio.NewReader(f)
+ b4, err := r4.Peek(5)
+ check(err)
+ fmt.Printf("5 bytes: %s\n", string(b4))
@@ -228,10 +209,8 @@ be scheduled immediately after Open
ing with
-
- f.Close()
-}
-
+ f.Close()
+}
@@ -245,15 +224,15 @@ be scheduled immediately after Open
ing with
- $ echo "hello" > /tmp/dat
-$ echo "go" >> /tmp/dat
-$ go run reading-files.go
-hello
-go
-5 bytes: hello
-2 bytes @ 6: go
-2 bytes @ 6: go
-5 bytes: hello
+ $ echo "hello" > /tmp/dat
+$ echo "go" >> /tmp/dat
+$ go run reading-files.go
+hello
+go
+5 bytes: hello
+2 bytes @ 6: go
+2 bytes @ 6: go
+5 bytes: hello
diff --git a/public/recover b/public/recover
index 903dbf8..b0d61c9 100644
--- a/public/recover
+++ b/public/recover
@@ -61,8 +61,7 @@ does by default for HTTP servers.

- package main
-
+ package main
@@ -72,8 +71,7 @@ does by default for HTTP servers.
- import "fmt"
-
+ import "fmt"
@@ -84,11 +82,9 @@ does by default for HTTP servers.
-
-func mayPanic() {
- panic("a problem")
-}
-
+ func mayPanic() {
+ panic("a problem")
+}
@@ -102,8 +98,7 @@ the panic.
- func main() {
-
+ func main() {
@@ -115,9 +110,8 @@ the call to panic
.
- defer func() {
- if r := recover(); r != nil {
-
+ defer func() {
+ if r := recover(); r != nil {
@@ -127,10 +121,9 @@ the call to panic
.
- fmt.Println("Recovered. Error:\n", r)
- }
- }()
-
+ fmt.Println("Recovered. Error:\n", r)
+ }
+ }()
@@ -140,8 +133,7 @@ the call to panic
.
- mayPanic()
-
+ mayPanic()
@@ -154,10 +146,8 @@ panic and resumes in the deferred closure.
-
- fmt.Println("After mayPanic()")
-}
-
+ fmt.Println("After mayPanic()")
+}
@@ -171,9 +161,9 @@ panic and resumes in the deferred closure.
- $ go run recover.go
-Recovered. Error:
- a problem
+ $ go run recover.go
+Recovered. Error:
+ a problem
diff --git a/public/recursion b/public/recursion
index 413b684..8b07370 100644
--- a/public/recursion
+++ b/public/recursion
@@ -44,8 +44,7 @@ Here’s a classic example.

- package main
-
+ package main
@@ -55,8 +54,7 @@ Here’s a classic example.
- import "fmt"
-
+ import "fmt"
@@ -68,14 +66,12 @@ base case of fact(0)
.
-
-func fact(n int) int {
- if n == 0 {
- return 1
- }
- return n * fact(n-1)
-}
-
+ func fact(n int) int {
+ if n == 0 {
+ return 1
+ }
+ return n * fact(n-1)
+}
@@ -85,9 +81,8 @@ base case of fact(0)
.
- func main() {
- fmt.Println(fact(7))
-
+ func main() {
+ fmt.Println(fact(7))
@@ -100,9 +95,7 @@ before it’s defined.
-
- var fib func(n int) int
-
+ var fib func(n int) int
@@ -112,11 +105,10 @@ before it’s defined.
- fib = func(n int) int {
- if n < 2 {
- return n
- }
-
+ fib = func(n int) int {
+ if n < 2 {
+ return n
+ }
@@ -128,10 +120,8 @@ knows which function to call with fib
here.
-
- return fib(n-1) + fib(n-2)
- }
-
+ return fib(n-1) + fib(n-2)
+ }
@@ -141,9 +131,8 @@ knows which function to call with fib
here.
- fmt.Println(fib(7))
-}
-
+ fmt.Println(fib(7))
+}
@@ -157,9 +146,9 @@ knows which function to call with fib
here.
- $ go run recursion.go
-5040
-13
+ $ go run recursion.go
+5040
+13
diff --git a/public/regular-expressions b/public/regular-expressions
index 9f830f0..43d6bea 100644
--- a/public/regular-expressions
+++ b/public/regular-expressions
@@ -44,8 +44,7 @@ in Go.

- package main
-
+ package main
@@ -55,12 +54,11 @@ in Go.
- import (
- "bytes"
- "fmt"
- "regexp"
-)
-
+ import (
+ "bytes"
+ "fmt"
+ "regexp"
+)
@@ -70,8 +68,7 @@ in Go.
- func main() {
-
+ func main() {
@@ -82,10 +79,8 @@ in Go.
-
- match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
- fmt.Println(match)
-
+ match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
+ fmt.Println(match)
@@ -98,9 +93,7 @@ optimized Regexp
struct.
-
- r, _ := regexp.Compile("p([a-z]+)ch")
-
+ r, _ := regexp.Compile("p([a-z]+)ch")
@@ -112,9 +105,7 @@ a match test like we saw earlier.
-
- fmt.Println(r.MatchString("peach"))
-
+ fmt.Println(r.MatchString("peach"))
@@ -125,9 +116,7 @@ a match test like we saw earlier.
-
- fmt.Println(r.FindString("peach punch"))
-
+ fmt.Println(r.FindString("peach punch"))
@@ -140,9 +129,7 @@ matching text.
-
- fmt.Println("idx:", r.FindStringIndex("peach punch"))
-
+ fmt.Println("idx:", r.FindStringIndex("peach punch"))
@@ -156,9 +143,7 @@ information for both p([a-z]+)ch
and ([a-z]+)
.
-
- fmt.Println(r.FindStringSubmatch("peach punch"))
-
+ fmt.Println(r.FindStringSubmatch("peach punch"))
@@ -170,9 +155,7 @@ indexes of matches and submatches.
-
- fmt.Println(r.FindStringSubmatchIndex("peach punch"))
-
+ fmt.Println(r.FindStringSubmatchIndex("peach punch"))
@@ -185,9 +168,7 @@ example to find all matches for a regexp.
-
- fmt.Println(r.FindAllString("peach punch pinch", -1))
-
+ fmt.Println(r.FindAllString("peach punch pinch", -1))
@@ -199,10 +180,8 @@ functions we saw above as well.
-
- fmt.Println("all:", r.FindAllStringSubmatchIndex(
- "peach punch pinch", -1))
-
+ fmt.Println("all:", r.FindAllStringSubmatchIndex(
+ "peach punch pinch", -1))
@@ -215,9 +194,7 @@ of matches.
-
- fmt.Println(r.FindAllString("peach punch pinch", 2))
-
+ fmt.Println(r.FindAllString("peach punch pinch", 2))
@@ -231,9 +208,7 @@ function name.
-
- fmt.Println(r.Match([]byte("peach")))
-
+ fmt.Println(r.Match([]byte("peach")))
@@ -248,10 +223,8 @@ global variables.
-
- r = regexp.MustCompile("p([a-z]+)ch")
- fmt.Println("regexp:", r)
-
+ r = regexp.MustCompile("p([a-z]+)ch")
+ fmt.Println("regexp:", r)
@@ -263,9 +236,7 @@ subsets of strings with other values.
-
- fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
-
+ fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
@@ -277,12 +248,10 @@ text with a given function.
-
- in := []byte("a peach")
- out := r.ReplaceAllFunc(in, bytes.ToUpper)
- fmt.Println(string(out))
-}
-
+ in := []byte("a peach")
+ out := r.ReplaceAllFunc(in, bytes.ToUpper)
+ fmt.Println(string(out))
+}
@@ -296,20 +265,20 @@ text with a given function.
- $ go run regular-expressions.go
-true
-true
-peach
-idx: [0 5]
-[peach ea]
-[0 5 1 3]
-[peach punch pinch]
-all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
-[peach punch]
-true
-regexp: p([a-z]+)ch
-a <fruit>
-a PEACH
+ $ go run regular-expressions.go
+true
+true
+peach
+idx: [0 5]
+[peach ea]
+[0 5 1 3]
+[peach punch pinch]
+all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
+[peach punch]
+true
+regexp: p([a-z]+)ch
+a <fruit>
+a PEACH
diff --git a/public/select b/public/select
index 8132666..7b660f9 100644
--- a/public/select
+++ b/public/select
@@ -44,8 +44,7 @@ select is a powerful feature of Go.

- package main
-
+ package main
@@ -55,11 +54,10 @@ select is a powerful feature of Go.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -69,8 +67,7 @@ select is a powerful feature of Go.
- func main() {
-
+ func main() {
@@ -81,10 +78,8 @@ select is a powerful feature of Go.
-
- c1 := make(chan string)
- c2 := make(chan string)
-
+ c1 := make(chan string)
+ c2 := make(chan string)
@@ -97,16 +92,14 @@ executing in concurrent goroutines.
-
- go func() {
- time.Sleep(1 * time.Second)
- c1 <- "one"
- }()
- go func() {
- time.Sleep(2 * time.Second)
- c2 <- "two"
- }()
-
+ go func() {
+ time.Sleep(1 * time.Second)
+ c1 <- "one"
+ }()
+ go func() {
+ time.Sleep(2 * time.Second)
+ c2 <- "two"
+ }()
@@ -118,17 +111,15 @@ simultaneously, printing each one as it arrives.
-
- for i := 0; i < 2; i++ {
- select {
- case msg1 := <-c1:
- fmt.Println("received", msg1)
- case msg2 := <-c2:
- fmt.Println("received", msg2)
- }
- }
-}
-
+ for i := 0; i < 2; i++ {
+ select {
+ case msg1 := <-c1:
+ fmt.Println("received", msg1)
+ case msg2 := <-c2:
+ fmt.Println("received", msg2)
+ }
+ }
+}
@@ -144,10 +135,9 @@ expected.
-
-$ time go run select.go
-received one
-received two
+ $ time go run select.go
+received one
+received two
@@ -160,8 +150,7 @@ concurrently.
-
-real 0m2.245s
+ real 0m2.245s
diff --git a/public/sha256-hashes b/public/sha256-hashes
index e1e1846..f05fd3c 100644
--- a/public/sha256-hashes
+++ b/public/sha256-hashes
@@ -46,8 +46,7 @@ SHA256 hashes in Go.

- package main
-
+ package main
@@ -59,12 +58,10 @@ SHA256 hashes in Go.
-
-import (
- "crypto/sha256"
- "fmt"
-)
-
+ import (
+ "crypto/sha256"
+ "fmt"
+)
@@ -74,9 +71,8 @@ SHA256 hashes in Go.
- func main() {
- s := "sha256 this string"
-
+ func main() {
+ s := "sha256 this string"
@@ -87,9 +83,7 @@ SHA256 hashes in Go.
-
- h := sha256.New()
-
+ h := sha256.New()
@@ -101,9 +95,7 @@ use []byte(s)
to coerce it to bytes.
-
- h.Write([]byte(s))
-
+ h.Write([]byte(s))
@@ -116,9 +108,7 @@ to an existing byte slice: it usually isn’t needed.
-
- bs := h.Sum(nil)
-
+ bs := h.Sum(nil)
@@ -128,10 +118,9 @@ to an existing byte slice: it usually isn’t needed.
- fmt.Println(s)
- fmt.Printf("%x\n", bs)
-}
-
+ fmt.Println(s)
+ fmt.Printf("%x\n", bs)
+}
@@ -147,10 +136,9 @@ a human-readable hex format.
-
-$ go run sha256-hashes.go
-sha256 this string
-1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
+ $ go run sha256-hashes.go
+sha256 this string
+1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
diff --git a/public/signals b/public/signals
index 42710f2..6f8e1ca 100644
--- a/public/signals
+++ b/public/signals
@@ -47,8 +47,7 @@ Here’s how to handle signals in Go with channels.

- package main
-
+ package main
@@ -58,13 +57,12 @@ Here’s how to handle signals in Go with channels.
- import (
- "fmt"
- "os"
- "os/signal"
- "syscall"
-)
-
+ import (
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+)
@@ -74,8 +72,7 @@ Here’s how to handle signals in Go with channels.
- func main() {
-
+ func main() {
@@ -89,9 +86,7 @@ should be buffered.
-
- sigs := make(chan os.Signal, 1)
-
+ sigs := make(chan os.Signal, 1)
@@ -103,9 +98,7 @@ receive notifications of the specified signals.
-
- signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
-
+ signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
@@ -119,9 +112,7 @@ a more realistic scenario of graceful shutdown.
-
- done := make(chan bool, 1)
-
+ done := make(chan bool, 1)
@@ -134,8 +125,7 @@ and then notify the program that it can finish.
- go func() {
-
+ go func() {
@@ -145,12 +135,11 @@ and then notify the program that it can finish.
- sig := <-sigs
- fmt.Println()
- fmt.Println(sig)
- done <- true
- }()
-
+ sig := <-sigs
+ fmt.Println()
+ fmt.Println(sig)
+ done <- true
+ }()
@@ -163,12 +152,10 @@ above sending a value on done
) and then exit.
-
- fmt.Println("awaiting signal")
- <-done
- fmt.Println("exiting")
-}
-
+ fmt.Println("awaiting signal")
+ <-done
+ fmt.Println("exiting")
+}
@@ -186,12 +173,11 @@ causing the program to print interrupt
and then exit.
-
-$ go run signals.go
-awaiting signal
-^C
-interrupt
-exiting
+ $ go run signals.go
+awaiting signal
+^C
+interrupt
+exiting
diff --git a/public/slices b/public/slices
index cee1ef5..f26101e 100644
--- a/public/slices
+++ b/public/slices
@@ -43,8 +43,7 @@ a more powerful interface to sequences than arrays.

- package main
-
+ package main
@@ -54,8 +53,7 @@ a more powerful interface to sequences than arrays.
- import "fmt"
-
+ import "fmt"
@@ -65,8 +63,7 @@ a more powerful interface to sequences than arrays.
- func main() {
-
+ func main() {
@@ -80,10 +77,8 @@ length 0.
-
- var s []string
- fmt.Println("uninit:", s, s == nil, len(s) == 0)
-
+ var s []string
+ fmt.Println("uninit:", s, s == nil, len(s) == 0)
@@ -100,10 +95,8 @@ as an additional parameter to make
.
-
- s = make([]string, 3)
- fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
-
+ s = make([]string, 3)
+ fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
@@ -114,13 +107,11 @@ as an additional parameter to make
.
-
- s[0] = "a"
- s[1] = "b"
- s[2] = "c"
- fmt.Println("set:", s)
- fmt.Println("get:", s[2])
-
+ s[0] = "a"
+ s[1] = "b"
+ s[2] = "c"
+ fmt.Println("set:", s)
+ fmt.Println("get:", s[2])
@@ -131,9 +122,7 @@ as an additional parameter to make
.
-
- fmt.Println("len:", len(s))
-
+ fmt.Println("len:", len(s))
@@ -149,11 +138,9 @@ Note that we need to accept a return value from
-
- s = append(s, "d")
- s = append(s, "e", "f")
- fmt.Println("apd:", s)
-
+ s = append(s, "d")
+ s = append(s, "e", "f")
+ fmt.Println("apd:", s)
@@ -166,11 +153,9 @@ into c
from s
.
-
- c := make([]string, len(s))
- copy(c, s)
- fmt.Println("cpy:", c)
-
+ c := make([]string, len(s))
+ copy(c, s)
+ fmt.Println("cpy:", c)
@@ -183,10 +168,8 @@ of the elements s[2]
, s[3]
, and s[4]
.
-
- l := s[2:5]
- fmt.Println("sl1:", l)
-
+ l := s[2:5]
+ fmt.Println("sl1:", l)
@@ -197,10 +180,8 @@ of the elements s[2]
, s[3]
, and s[4]
.
-
- l = s[:5]
- fmt.Println("sl2:", l)
-
+ l = s[:5]
+ fmt.Println("sl2:", l)
@@ -211,10 +192,8 @@ of the elements s[2]
, s[3]
, and s[4]
.
-
- l = s[2:]
- fmt.Println("sl3:", l)
-
+ l = s[2:]
+ fmt.Println("sl3:", l)
@@ -226,10 +205,8 @@ in a single line as well.
-
- t := []string{"g", "h", "i"}
- fmt.Println("dcl:", t)
-
+ t := []string{"g", "h", "i"}
+ fmt.Println("dcl:", t)
@@ -242,18 +219,16 @@ vary, unlike with multi-dimensional arrays.
-
- twoD := make([][]int, 3)
- for i := 0; i < 3; i++ {
- innerLen := i + 1
- twoD[i] = make([]int, innerLen)
- for j := 0; j < innerLen; j++ {
- twoD[i][j] = i + j
- }
- }
- fmt.Println("2d: ", twoD)
-}
-
+ twoD := make([][]int, 3)
+ for i := 0; i < 3; i++ {
+ innerLen := i + 1
+ twoD[i] = make([]int, innerLen)
+ for j := 0; j < innerLen; j++ {
+ twoD[i][j] = i + j
+ }
+ }
+ fmt.Println("2d: ", twoD)
+}
@@ -269,20 +244,19 @@ they are rendered similarly by fmt.Println
.
-
-$ go run slices.go
-uninit: [] true true
-emp: [ ] len: 3 cap: 3
-set: [a b c]
-get: c
-len: 3
-apd: [a b c d e f]
-cpy: [a b c d e f]
-sl1: [c d e]
-sl2: [a b c d e]
-sl3: [c d e f]
-dcl: [g h i]
-2d: [[0] [1 2] [2 3 4]]
+ $ go run slices.go
+uninit: [] true true
+emp: [ ] len: 3 cap: 3
+set: [a b c]
+get: c
+len: 3
+apd: [a b c d e f]
+cpy: [a b c d e f]
+sl1: [c d e]
+sl2: [a b c d e]
+sl3: [c d e f]
+dcl: [g h i]
+2d: [[0] [1 2] [2 3 4]]
diff --git a/public/sorting b/public/sorting
index e3c3508..866ca5d 100644
--- a/public/sorting
+++ b/public/sorting
@@ -44,8 +44,7 @@ builtins first.

- package main
-
+ package main
@@ -55,11 +54,10 @@ builtins first.
- import (
- "fmt"
- "sort"
-)
-
+ import (
+ "fmt"
+ "sort"
+)
@@ -69,8 +67,7 @@ builtins first.
- func main() {
-
+ func main() {
@@ -84,11 +81,9 @@ return a new one.
-
- strs := []string{"c", "a", "b"}
- sort.Strings(strs)
- fmt.Println("Strings:", strs)
-
+ strs := []string{"c", "a", "b"}
+ sort.Strings(strs)
+ fmt.Println("Strings:", strs)
@@ -99,11 +94,9 @@ return a new one.
-
- ints := []int{7, 2, 4}
- sort.Ints(ints)
- fmt.Println("Ints: ", ints)
-
+ ints := []int{7, 2, 4}
+ sort.Ints(ints)
+ fmt.Println("Ints: ", ints)
@@ -115,11 +108,9 @@ already in sorted order.
-
- s := sort.IntsAreSorted(ints)
- fmt.Println("Sorted: ", s)
-}
-
+ s := sort.IntsAreSorted(ints)
+ fmt.Println("Sorted: ", s)
+}
@@ -135,11 +126,10 @@ slices and true
as the result of our AreSorted
test.
-
-$ go run sorting.go
-Strings: [a b c]
-Ints: [2 4 7]
-Sorted: true
+ $ go run sorting.go
+Strings: [a b c]
+Ints: [2 4 7]
+Sorted: true
diff --git a/public/sorting-by-functions b/public/sorting-by-functions
index 1607ffa..77b833c 100644
--- a/public/sorting-by-functions
+++ b/public/sorting-by-functions
@@ -46,8 +46,7 @@ in Go.

- package main
-
+ package main
@@ -57,11 +56,10 @@ in Go.
- import (
- "fmt"
- "sort"
-)
-
+ import (
+ "fmt"
+ "sort"
+)
@@ -75,9 +73,7 @@ type.
-
-type byLength []string
-
+ type byLength []string
@@ -94,17 +90,15 @@ we use len(s[i])
and len(s[j])
here.
-
-func (s byLength) Len() int {
- return len(s)
-}
-func (s byLength) Swap(i, j int) {
- s[i], s[j] = s[j], s[i]
-}
-func (s byLength) Less(i, j int) bool {
- return len(s[i]) < len(s[j])
-}
-
+ func (s byLength) Len() int {
+ return len(s)
+}
+func (s byLength) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+func (s byLength) Less(i, j int) bool {
+ return len(s[i]) < len(s[j])
+}
@@ -118,13 +112,11 @@ slice.
-
-func main() {
- fruits := []string{"peach", "banana", "kiwi"}
- sort.Sort(byLength(fruits))
- fmt.Println(fruits)
-}
-
+ func main() {
+ fruits := []string{"peach", "banana", "kiwi"}
+ sort.Sort(byLength(fruits))
+ fmt.Println(fruits)
+}
@@ -140,9 +132,8 @@ length, as desired.
-
-$ go run sorting-by-functions.go
-[kiwi peach banana]
+ $ go run sorting-by-functions.go
+[kiwi peach banana]
diff --git a/public/spawning-processes b/public/spawning-processes
index d013fc1..5c48a43 100644
--- a/public/spawning-processes
+++ b/public/spawning-processes
@@ -43,8 +43,7 @@ processes.

- package main
-
+ package main
@@ -54,12 +53,11 @@ processes.
- import (
- "fmt"
- "io"
- "os/exec"
-)
-
+ import (
+ "fmt"
+ "io"
+ "os/exec"
+)
@@ -69,8 +67,7 @@ processes.
- func main() {
-
+ func main() {
@@ -84,9 +81,7 @@ to represent this external process.
-
- dateCmd := exec.Command("date")
-
+ dateCmd := exec.Command("date")
@@ -100,14 +95,12 @@ with the date info.
-
- dateOut, err := dateCmd.Output()
- if err != nil {
- panic(err)
- }
- fmt.Println("> date")
- fmt.Println(string(dateOut))
-
+ dateOut, err := dateCmd.Output()
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println("> date")
+ fmt.Println(string(dateOut))
@@ -122,19 +115,17 @@ code.
-
- _, err = exec.Command("date", "-x").Output()
- if err != nil {
- switch e := err.(type) {
- case *exec.Error:
- fmt.Println("failed executing:", err)
- case *exec.ExitError:
- fmt.Println("command exit rc =", e.ExitCode())
- default:
- panic(err)
- }
- }
-
+ _, err = exec.Command("date", "-x").Output()
+ if err != nil {
+ switch e := err.(type) {
+ case *exec.Error:
+ fmt.Println("failed executing:", err)
+ case *exec.ExitError:
+ fmt.Println("command exit rc =", e.ExitCode())
+ default:
+ panic(err)
+ }
+ }
@@ -147,9 +138,7 @@ where we pipe data to the external process on its
-
- grepCmd := exec.Command("grep", "hello")
-
+ grepCmd := exec.Command("grep", "hello")
@@ -163,15 +152,13 @@ to exit.
-
- grepIn, _ := grepCmd.StdinPipe()
- grepOut, _ := grepCmd.StdoutPipe()
- grepCmd.Start()
- grepIn.Write([]byte("hello grep\ngoodbye grep"))
- grepIn.Close()
- grepBytes, _ := io.ReadAll(grepOut)
- grepCmd.Wait()
-
+ grepIn, _ := grepCmd.StdinPipe()
+ grepOut, _ := grepCmd.StdoutPipe()
+ grepCmd.Start()
+ grepIn.Write([]byte("hello grep\ngoodbye grep"))
+ grepIn.Close()
+ grepBytes, _ := io.ReadAll(grepOut)
+ grepCmd.Wait()
@@ -186,10 +173,8 @@ exactly the same way.
-
- fmt.Println("> grep hello")
- fmt.Println(string(grepBytes))
-
+ fmt.Println("> grep hello")
+ fmt.Println(string(grepBytes))
@@ -205,16 +190,14 @@ option:
-
- lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
- lsOut, err := lsCmd.Output()
- if err != nil {
- panic(err)
- }
- fmt.Println("> ls -a -l -h")
- fmt.Println(string(lsOut))
-}
-
+ lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
+ lsOut, err := lsCmd.Output()
+ if err != nil {
+ panic(err)
+ }
+ fmt.Println("> ls -a -l -h")
+ fmt.Println(string(lsOut))
+}
@@ -230,10 +213,9 @@ as if we had run them directly from the command-line.
-
-$ go run spawning-processes.go
-> date
-Thu 05 May 2022 10:10:12 PM PDT
+ $ go run spawning-processes.go
+> date
+Thu 05 May 2022 10:10:12 PM PDT
@@ -245,10 +227,9 @@ an error message and non-zero return code.
-
-command exited with rc = 1
-> grep hello
-hello grep
+ command exited with rc = 1
+> grep hello
+hello grep
@@ -258,10 +239,10 @@ an error message and non-zero return code.
- > ls -a -l -h
-drwxr-xr-x 4 mark 136B Oct 3 16:29 .
-drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
--rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go
+ > ls -a -l -h
+drwxr-xr-x 4 mark 136B Oct 3 16:29 .
+drwxr-xr-x 91 mark 3.0K Oct 3 12:50 ..
+-rw-r--r-- 1 mark 1.3K Oct 3 16:28 spawning-processes.go
diff --git a/public/stateful-goroutines b/public/stateful-goroutines
index 119f08b..d443072 100644
--- a/public/stateful-goroutines
+++ b/public/stateful-goroutines
@@ -49,8 +49,7 @@ by exactly 1 goroutine.

- package main
-
+ package main
@@ -60,13 +59,12 @@ by exactly 1 goroutine.
- import (
- "fmt"
- "math/rand"
- "sync/atomic"
- "time"
-)
-
+ import (
+ "fmt"
+ "math/rand"
+ "sync/atomic"
+ "time"
+)
@@ -84,17 +82,15 @@ goroutine to respond.
-
-type readOp struct {
- key int
- resp chan int
-}
-type writeOp struct {
- key int
- val int
- resp chan bool
-}
-
+ type readOp struct {
+ key int
+ resp chan int
+}
+type writeOp struct {
+ key int
+ val int
+ resp chan bool
+}
@@ -104,8 +100,7 @@ goroutine to respond.
- func main() {
-
+ func main() {
@@ -116,10 +111,8 @@ goroutine to respond.
-
- var readOps uint64
- var writeOps uint64
-
+ var readOps uint64
+ var writeOps uint64
@@ -132,10 +125,8 @@ respectively.
-
- reads := make(chan readOp)
- writes := make(chan writeOp)
-
+ reads := make(chan readOp)
+ writes := make(chan writeOp)
@@ -154,20 +145,18 @@ value in the case of reads
).
-
- go func() {
- var state = make(map[int]int)
- for {
- select {
- case read := <-reads:
- read.resp <- state[read.key]
- case write := <-writes:
- state[write.key] = write.val
- write.resp <- true
- }
- }
- }()
-
+ go func() {
+ var state = make(map[int]int)
+ for {
+ select {
+ case read := <-reads:
+ read.resp <- state[read.key]
+ case write := <-writes:
+ state[write.key] = write.val
+ write.resp <- true
+ }
+ }
+ }()
@@ -182,21 +171,19 @@ result over the provided resp
channel.
-
- for r := 0; r < 100; r++ {
- go func() {
- for {
- read := readOp{
- key: rand.Intn(5),
- resp: make(chan int)}
- reads <- read
- <-read.resp
- atomic.AddUint64(&readOps, 1)
- time.Sleep(time.Millisecond)
- }
- }()
- }
-
+ for r := 0; r < 100; r++ {
+ go func() {
+ for {
+ read := readOp{
+ key: rand.Intn(5),
+ resp: make(chan int)}
+ reads <- read
+ <-read.resp
+ atomic.AddUint64(&readOps, 1)
+ time.Sleep(time.Millisecond)
+ }
+ }()
+ }
@@ -208,22 +195,20 @@ approach.
-
- for w := 0; w < 10; w++ {
- go func() {
- for {
- write := writeOp{
- key: rand.Intn(5),
- val: rand.Intn(100),
- resp: make(chan bool)}
- writes <- write
- <-write.resp
- atomic.AddUint64(&writeOps, 1)
- time.Sleep(time.Millisecond)
- }
- }()
- }
-
+ for w := 0; w < 10; w++ {
+ go func() {
+ for {
+ write := writeOp{
+ key: rand.Intn(5),
+ val: rand.Intn(100),
+ resp: make(chan bool)}
+ writes <- write
+ <-write.resp
+ atomic.AddUint64(&writeOps, 1)
+ time.Sleep(time.Millisecond)
+ }
+ }()
+ }
@@ -234,9 +219,7 @@ approach.
-
- time.Sleep(time.Second)
-
+ time.Sleep(time.Second)
@@ -247,13 +230,11 @@ approach.
-
- readOpsFinal := atomic.LoadUint64(&readOps)
- fmt.Println("readOps:", readOpsFinal)
- writeOpsFinal := atomic.LoadUint64(&writeOps)
- fmt.Println("writeOps:", writeOpsFinal)
-}
-
+ readOpsFinal := atomic.LoadUint64(&readOps)
+ fmt.Println("readOps:", readOpsFinal)
+ writeOpsFinal := atomic.LoadUint64(&writeOps)
+ fmt.Println("writeOps:", writeOpsFinal)
+}
@@ -270,10 +251,9 @@ total operations.
-
-$ go run stateful-goroutines.go
-readOps: 71708
-writeOps: 7177
+ $ go run stateful-goroutines.go
+readOps: 71708
+writeOps: 7177
diff --git a/public/string-formatting b/public/string-formatting
index eb6b45b..1d98485 100644
--- a/public/string-formatting
+++ b/public/string-formatting
@@ -44,8 +44,7 @@ common string formatting tasks.

- package main
-
+ package main
@@ -55,11 +54,10 @@ common string formatting tasks.
- import (
- "fmt"
- "os"
-)
-
+ import (
+ "fmt"
+ "os"
+)
@@ -69,10 +67,9 @@ common string formatting tasks.
- type point struct {
- x, y int
-}
-
+ type point struct {
+ x, y int
+}
@@ -82,8 +79,7 @@ common string formatting tasks.
- func main() {
-
+ func main() {
@@ -96,10 +92,8 @@ an instance of our point
struct.
-
- p := point{1, 2}
- fmt.Printf("struct1: %v\n", p)
-
+ p := point{1, 2}
+ fmt.Printf("struct1: %v\n", p)
@@ -111,9 +105,7 @@ include the struct’s field names.
-
- fmt.Printf("struct2: %+v\n", p)
-
+ fmt.Printf("struct2: %+v\n", p)
@@ -126,9 +118,7 @@ would produce that value.
-
- fmt.Printf("struct3: %#v\n", p)
-
+ fmt.Printf("struct3: %#v\n", p)
@@ -139,9 +129,7 @@ would produce that value.
-
- fmt.Printf("type: %T\n", p)
-
+ fmt.Printf("type: %T\n", p)
@@ -152,9 +140,7 @@ would produce that value.
-
- fmt.Printf("bool: %t\n", true)
-
+ fmt.Printf("bool: %t\n", true)
@@ -166,9 +152,7 @@ Use %d
for standard, base-10 formatting.
-
- fmt.Printf("int: %d\n", 123)
-
+ fmt.Printf("int: %d\n", 123)
@@ -179,9 +163,7 @@ Use %d
for standard, base-10 formatting.
-
- fmt.Printf("bin: %b\n", 14)
-
+ fmt.Printf("bin: %b\n", 14)
@@ -193,9 +175,7 @@ given integer.
-
- fmt.Printf("char: %c\n", 33)
-
+ fmt.Printf("char: %c\n", 33)
@@ -206,9 +186,7 @@ given integer.
-
- fmt.Printf("hex: %x\n", 456)
-
+ fmt.Printf("hex: %x\n", 456)
@@ -220,9 +198,7 @@ floats. For basic decimal formatting use %f
.
-
- fmt.Printf("float1: %f\n", 78.9)
-
+ fmt.Printf("float1: %f\n", 78.9)
@@ -234,10 +210,8 @@ different versions of) scientific notation.
-
- fmt.Printf("float2: %e\n", 123400000.0)
- fmt.Printf("float3: %E\n", 123400000.0)
-
+ fmt.Printf("float2: %e\n", 123400000.0)
+ fmt.Printf("float3: %E\n", 123400000.0)
@@ -248,9 +222,7 @@ different versions of) scientific notation.
-
- fmt.Printf("str1: %s\n", "\"string\"")
-
+ fmt.Printf("str1: %s\n", "\"string\"")
@@ -261,9 +233,7 @@ different versions of) scientific notation.
-
- fmt.Printf("str2: %q\n", "\"string\"")
-
+ fmt.Printf("str2: %q\n", "\"string\"")
@@ -276,9 +246,7 @@ per byte of input.
-
- fmt.Printf("str3: %x\n", "hex this")
-
+ fmt.Printf("str3: %x\n", "hex this")
@@ -289,9 +257,7 @@ per byte of input.
-
- fmt.Printf("pointer: %p\n", &p)
-
+ fmt.Printf("pointer: %p\n", &p)
@@ -307,9 +273,7 @@ spaces.
-
- fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
-
+ fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
@@ -323,9 +287,7 @@ width.precision syntax.
-
- fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
-
+ fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
@@ -336,9 +298,7 @@ width.precision syntax.
-
- fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
-
+ fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
@@ -351,9 +311,7 @@ table-like output. For basic right-justified width.
-
- fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
-
+ fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
@@ -364,9 +322,7 @@ table-like output. For basic right-justified width.
-
- fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
-
+ fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
@@ -379,10 +335,8 @@ and returns a string without printing it anywhere.
-
- s := fmt.Sprintf("sprintf: a %s", "string")
- fmt.Println(s)
-
+ s := fmt.Sprintf("sprintf: a %s", "string")
+ fmt.Println(s)
@@ -394,10 +348,8 @@ and returns a string without printing it anywhere.
-
- fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
-}
-
+ fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
+}
@@ -411,30 +363,30 @@ and returns a string without printing it anywhere.
- $ go run string-formatting.go
-struct1: {1 2}
-struct2: {x:1 y:2}
-struct3: main.point{x:1, y:2}
-type: main.point
-bool: true
-int: 123
-bin: 1110
-char: !
-hex: 1c8
-float1: 78.900000
-float2: 1.234000e+08
-float3: 1.234000E+08
-str1: "string"
-str2: "\"string\""
-str3: 6865782074686973
-pointer: 0xc0000ba000
-width1: | 12| 345|
-width2: | 1.20| 3.45|
-width3: |1.20 |3.45 |
-width4: | foo| b|
-width5: |foo |b |
-sprintf: a string
-io: an error
+ $ go run string-formatting.go
+struct1: {1 2}
+struct2: {x:1 y:2}
+struct3: main.point{x:1, y:2}
+type: main.point
+bool: true
+int: 123
+bin: 1110
+char: !
+hex: 1c8
+float1: 78.900000
+float2: 1.234000e+08
+float3: 1.234000E+08
+str1: "string"
+str2: "\"string\""
+str3: 6865782074686973
+pointer: 0xc0000ba000
+width1: | 12| 345|
+width2: | 1.20| 3.45|
+width3: |1.20 |3.45 |
+width4: | foo| b|
+width5: |foo |b |
+sprintf: a string
+io: an error
diff --git a/public/string-functions b/public/string-functions
index 0b38f93..b5f7215 100644
--- a/public/string-functions
+++ b/public/string-functions
@@ -44,8 +44,7 @@ to give you a sense of the package.

- package main
-
+ package main
@@ -55,11 +54,10 @@ to give you a sense of the package.
- import (
- "fmt"
- s "strings"
-)
-
+ import (
+ "fmt"
+ s "strings"
+)
@@ -71,9 +69,7 @@ it a lot below.
-
-var p = fmt.Println
-
+ var p = fmt.Println
@@ -83,8 +79,7 @@ it a lot below.
- func main() {
-
+ func main() {
@@ -101,21 +96,19 @@ package docs.
-
- p("Contains: ", s.Contains("test", "es"))
- p("Count: ", s.Count("test", "t"))
- p("HasPrefix: ", s.HasPrefix("test", "te"))
- p("HasSuffix: ", s.HasSuffix("test", "st"))
- p("Index: ", s.Index("test", "e"))
- p("Join: ", s.Join([]string{"a", "b"}, "-"))
- p("Repeat: ", s.Repeat("a", 5))
- p("Replace: ", s.Replace("foo", "o", "0", -1))
- p("Replace: ", s.Replace("foo", "o", "0", 1))
- p("Split: ", s.Split("a-b-c-d-e", "-"))
- p("ToLower: ", s.ToLower("TEST"))
- p("ToUpper: ", s.ToUpper("test"))
-}
-
+ p("Contains: ", s.Contains("test", "es"))
+ p("Count: ", s.Count("test", "t"))
+ p("HasPrefix: ", s.HasPrefix("test", "te"))
+ p("HasSuffix: ", s.HasSuffix("test", "st"))
+ p("Index: ", s.Index("test", "e"))
+ p("Join: ", s.Join([]string{"a", "b"}, "-"))
+ p("Repeat: ", s.Repeat("a", 5))
+ p("Replace: ", s.Replace("foo", "o", "0", -1))
+ p("Replace: ", s.Replace("foo", "o", "0", 1))
+ p("Split: ", s.Split("a-b-c-d-e", "-"))
+ p("ToLower: ", s.ToLower("TEST"))
+ p("ToUpper: ", s.ToUpper("test"))
+}
@@ -129,19 +122,19 @@ package docs.
- $ go run string-functions.go
-Contains: true
-Count: 2
-HasPrefix: true
-HasSuffix: true
-Index: 1
-Join: a-b
-Repeat: aaaaa
-Replace: f00
-Replace: f0o
-Split: [a b c d e]
-ToLower: test
-ToUpper: TEST
+ $ go run string-functions.go
+Contains: true
+Count: 2
+HasPrefix: true
+HasSuffix: true
+Index: 1
+Join: a-b
+Repeat: aaaaa
+Replace: f00
+Replace: f0o
+Split: [a b c d e]
+ToLower: test
+ToUpper: TEST
diff --git a/public/strings-and-runes b/public/strings-and-runes
index 9fe20ec..f5bf97e 100644
--- a/public/strings-and-runes
+++ b/public/strings-and-runes
@@ -49,8 +49,7 @@ introduction to the topic.

- package main
-
+ package main
@@ -60,11 +59,10 @@ introduction to the topic.
- import (
- "fmt"
- "unicode/utf8"
-)
-
+ import (
+ "fmt"
+ "unicode/utf8"
+)
@@ -74,8 +72,7 @@ introduction to the topic.
- func main() {
-
+ func main() {
@@ -89,9 +86,7 @@ encoded text.
-
- const s = "สวัสดี"
-
+ const s = "สวัสดี"
@@ -103,9 +98,7 @@ will produce the length of the raw bytes stored within.
-
- fmt.Println("Len:", len(s))
-
+ fmt.Println("Len:", len(s))
@@ -118,12 +111,10 @@ the bytes that constitute the code points in s
.
-
- for i := 0; i < len(s); i++ {
- fmt.Printf("%x ", s[i])
- }
- fmt.Println()
-
+ for i := 0; i < len(s); i++ {
+ fmt.Printf("%x ", s[i])
+ }
+ fmt.Println()
@@ -139,9 +130,7 @@ code points, so the result of this count may be surprising.
-
- fmt.Println("Rune count:", utf8.RuneCountInString(s))
-
+ fmt.Println("Rune count:", utf8.RuneCountInString(s))
@@ -153,11 +142,9 @@ each rune
along with its offset in the string.
-
- for idx, runeValue := range s {
- fmt.Printf("%#U starts at %d\n", runeValue, idx)
- }
-
+ for idx, runeValue := range s {
+ fmt.Printf("%#U starts at %d\n", runeValue, idx)
+ }
@@ -169,13 +156,11 @@ each rune
along with its offset in the string.
-
- fmt.Println("\nUsing DecodeRuneInString")
- for i, w := 0, 0; i < len(s); i += w {
- runeValue, width := utf8.DecodeRuneInString(s[i:])
- fmt.Printf("%#U starts at %d\n", runeValue, i)
- w = width
-
+ fmt.Println("\nUsing DecodeRuneInString")
+ for i, w := 0, 0; i < len(s); i += w {
+ runeValue, width := utf8.DecodeRuneInString(s[i:])
+ fmt.Printf("%#U starts at %d\n", runeValue, i)
+ w = width
@@ -186,11 +171,9 @@ each rune
along with its offset in the string.
-
- examineRune(runeValue)
- }
-}
-
+ examineRune(runeValue)
+ }
+}
@@ -200,8 +183,7 @@ each rune
along with its offset in the string.
- func examineRune(r rune) {
-
+ func examineRune(r rune) {
@@ -213,14 +195,12 @@ can compare a rune
value to a rune literal directly.
-
- if r == 't' {
- fmt.Println("found tee")
- } else if r == 'ส' {
- fmt.Println("found so sua")
- }
-}
-
+ if r == 't' {
+ fmt.Println("found tee")
+ } else if r == 'ส' {
+ fmt.Println("found so sua")
+ }
+}
@@ -234,16 +214,16 @@ can compare a rune
value to a rune literal directly.
- $ go run strings-and-runes.go
-Len: 18
-e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5
-Rune count: 6
-U+0E2A 'ส' starts at 0
-U+0E27 'ว' starts at 3
-U+0E31 'ั' starts at 6
-U+0E2A 'ส' starts at 9
-U+0E14 'ด' starts at 12
-U+0E35 'ี' starts at 15
+ $ go run strings-and-runes.go
+Len: 18
+e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5
+Rune count: 6
+U+0E2A 'ส' starts at 0
+U+0E27 'ว' starts at 3
+U+0E31 'ั' starts at 6
+U+0E2A 'ส' starts at 9
+U+0E14 'ด' starts at 12
+U+0E35 'ี' starts at 15
@@ -253,15 +233,15 @@ can compare a rune
value to a rune literal directly.
- Using DecodeRuneInString
-U+0E2A 'ส' starts at 0
-found so sua
-U+0E27 'ว' starts at 3
-U+0E31 'ั' starts at 6
-U+0E2A 'ส' starts at 9
-found so sua
-U+0E14 'ด' starts at 12
-U+0E35 'ี' starts at 15
+ Using DecodeRuneInString
+U+0E2A 'ส' starts at 0
+found so sua
+U+0E27 'ว' starts at 3
+U+0E31 'ั' starts at 6
+U+0E2A 'ส' starts at 9
+found so sua
+U+0E14 'ด' starts at 12
+U+0E35 'ี' starts at 15
diff --git a/public/struct-embedding b/public/struct-embedding
index e10cd67..40b5fe9 100644
--- a/public/struct-embedding
+++ b/public/struct-embedding
@@ -46,8 +46,7 @@ files and folders into the application binary.

- package main
-
+ package main
@@ -57,8 +56,7 @@ files and folders into the application binary.
- import "fmt"
-
+ import "fmt"
@@ -68,10 +66,9 @@ files and folders into the application binary.
- type base struct {
- num int
-}
-
+ type base struct {
+ num int
+}
@@ -81,10 +78,9 @@ files and folders into the application binary.
- func (b base) describe() string {
- return fmt.Sprintf("base with num=%v", b.num)
-}
-
+ func (b base) describe() string {
+ return fmt.Sprintf("base with num=%v", b.num)
+}
@@ -96,12 +92,10 @@ like a field without a name.
-
-type container struct {
- base
- str string
-}
-
+ type container struct {
+ base
+ str string
+}
@@ -111,8 +105,7 @@ like a field without a name.
- func main() {
-
+ func main() {
@@ -125,14 +118,12 @@ embedded type serves as the field name.
-
- co := container{
- base: base{
- num: 1,
- },
- str: "some name",
- }
-
+ co := container{
+ base: base{
+ num: 1,
+ },
+ str: "some name",
+ }
@@ -144,9 +135,7 @@ e.g. co.num
.
-
- fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
-
+ fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
@@ -158,9 +147,7 @@ the embedded type name.
-
- fmt.Println("also num:", co.base.num)
-
+ fmt.Println("also num:", co.base.num)
@@ -174,9 +161,7 @@ directly on co
.
-
- fmt.Println("describe:", co.describe())
-
+ fmt.Println("describe:", co.describe())
@@ -186,10 +171,9 @@ directly on co
.
- type describer interface {
- describe() string
- }
-
+ type describer interface {
+ describe() string
+ }
@@ -203,11 +187,9 @@ we see that a container
now implements the
-
- var d describer = co
- fmt.Println("describer:", d.describe())
-}
-
+ var d describer = co
+ fmt.Println("describer:", d.describe())
+}
@@ -221,11 +203,11 @@ we see that a container
now implements the
- $ go run struct-embedding.go
-co={num: 1, str: some name}
-also num: 1
-describe: base with num=1
-describer: base with num=1
+ $ go run struct-embedding.go
+co={num: 1, str: some name}
+also num: 1
+describe: base with num=1
+describer: base with num=1
diff --git a/public/structs b/public/structs
index 40e92df..15a573a 100644
--- a/public/structs
+++ b/public/structs
@@ -44,8 +44,7 @@ records.

- package main
-
+ package main
@@ -55,8 +54,7 @@ records.
- import "fmt"
-
+ import "fmt"
@@ -67,12 +65,10 @@ records.
-
-type person struct {
- name string
- age int
-}
-
+ type person struct {
+ name string
+ age int
+}
@@ -83,9 +79,7 @@ records.
-
-func newPerson(name string) *person {
-
+ func newPerson(name string) *person {
@@ -97,12 +91,10 @@ as a local variable will survive the scope of the function.
-
- p := person{name: name}
- p.age = 42
- return &p
-}
-
+ p := person{name: name}
+ p.age = 42
+ return &p
+}
@@ -112,8 +104,7 @@ as a local variable will survive the scope of the function.
- func main() {
-
+ func main() {
@@ -124,9 +115,7 @@ as a local variable will survive the scope of the function.
-
- fmt.Println(person{"Bob", 20})
-
+ fmt.Println(person{"Bob", 20})
@@ -137,9 +126,7 @@ as a local variable will survive the scope of the function.
-
- fmt.Println(person{name: "Alice", age: 30})
-
+ fmt.Println(person{name: "Alice", age: 30})
@@ -150,9 +137,7 @@ as a local variable will survive the scope of the function.
-
- fmt.Println(person{name: "Fred"})
-
+ fmt.Println(person{name: "Fred"})
@@ -163,9 +148,7 @@ as a local variable will survive the scope of the function.
-
- fmt.Println(&person{name: "Ann", age: 40})
-
+ fmt.Println(&person{name: "Ann", age: 40})
@@ -176,9 +159,7 @@ as a local variable will survive the scope of the function.
-
- fmt.Println(newPerson("Jon"))
-
+ fmt.Println(newPerson("Jon"))
@@ -189,10 +170,8 @@ as a local variable will survive the scope of the function.
-
- s := person{name: "Sean", age: 50}
- fmt.Println(s.name)
-
+ s := person{name: "Sean", age: 50}
+ fmt.Println(s.name)
@@ -204,10 +183,8 @@ pointers are automatically dereferenced.
-
- sp := &s
- fmt.Println(sp.age)
-
+ sp := &s
+ fmt.Println(sp.age)
@@ -218,10 +195,8 @@ pointers are automatically dereferenced.
-
- sp.age = 51
- fmt.Println(sp.age)
-
+ sp.age = 51
+ fmt.Println(sp.age)
@@ -235,17 +210,15 @@ struct type. This technique is commonly used for
-
- dog := struct {
- name string
- isGood bool
- }{
- "Rex",
- true,
- }
- fmt.Println(dog)
-}
-
+ dog := struct {
+ name string
+ isGood bool
+ }{
+ "Rex",
+ true,
+ }
+ fmt.Println(dog)
+}
@@ -259,16 +232,16 @@ struct type. This technique is commonly used for
- $ go run structs.go
-{Bob 20}
-{Alice 30}
-{Fred 0}
-&{Ann 40}
-&{Jon 42}
-Sean
-50
-51
-{Rex true}
+ $ go run structs.go
+{Bob 20}
+{Alice 30}
+{Fred 0}
+&{Ann 40}
+&{Jon 42}
+Sean
+50
+51
+{Rex true}
diff --git a/public/switch b/public/switch
index aaab93d..947a66f 100644
--- a/public/switch
+++ b/public/switch
@@ -43,8 +43,7 @@ branches.

- package main
-
+ package main
@@ -54,11 +53,10 @@ branches.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -68,8 +66,7 @@ branches.
- func main() {
-
+ func main() {
@@ -80,18 +77,16 @@ branches.
-
- i := 2
- fmt.Print("Write ", i, " as ")
- switch i {
- case 1:
- fmt.Println("one")
- case 2:
- fmt.Println("two")
- case 3:
- fmt.Println("three")
- }
-
+ i := 2
+ fmt.Print("Write ", i, " as ")
+ switch i {
+ case 1:
+ fmt.Println("one")
+ case 2:
+ fmt.Println("two")
+ case 3:
+ fmt.Println("three")
+ }
@@ -104,14 +99,12 @@ in the same case
statement. We use the optional
-
- switch time.Now().Weekday() {
- case time.Saturday, time.Sunday:
- fmt.Println("It's the weekend")
- default:
- fmt.Println("It's a weekday")
- }
-
+ switch time.Now().Weekday() {
+ case time.Saturday, time.Sunday:
+ fmt.Println("It's the weekend")
+ default:
+ fmt.Println("It's a weekday")
+ }
@@ -124,15 +117,13 @@ to express if/else logic. Here we also show how the
-
- t := time.Now()
- switch {
- case t.Hour() < 12:
- fmt.Println("It's before noon")
- default:
- fmt.Println("It's after noon")
- }
-
+ t := time.Now()
+ switch {
+ case t.Hour() < 12:
+ fmt.Println("It's before noon")
+ default:
+ fmt.Println("It's after noon")
+ }
@@ -146,22 +137,20 @@ type corresponding to its clause.
-
- whatAmI := func(i interface{}) {
- switch t := i.(type) {
- case bool:
- fmt.Println("I'm a bool")
- case int:
- fmt.Println("I'm an int")
- default:
- fmt.Printf("Don't know type %T\n", t)
- }
- }
- whatAmI(true)
- whatAmI(1)
- whatAmI("hey")
-}
-
+ whatAmI := func(i interface{}) {
+ switch t := i.(type) {
+ case bool:
+ fmt.Println("I'm a bool")
+ case int:
+ fmt.Println("I'm an int")
+ default:
+ fmt.Printf("Don't know type %T\n", t)
+ }
+ }
+ whatAmI(true)
+ whatAmI(1)
+ whatAmI("hey")
+}
@@ -175,13 +164,13 @@ type corresponding to its clause.
- $ go run switch.go
-Write 2 as two
-It's a weekday
-It's after noon
-I'm a bool
-I'm an int
-Don't know type string
+ $ go run switch.go
+Write 2 as two
+It's a weekday
+It's after noon
+I'm a bool
+I'm an int
+Don't know type string
diff --git a/public/temporary-files-and-directories b/public/temporary-files-and-directories
index fc173a7..bcb0354 100644
--- a/public/temporary-files-and-directories
+++ b/public/temporary-files-and-directories
@@ -46,8 +46,7 @@ time.

- package main
-
+ package main
@@ -57,12 +56,11 @@ time.
- import (
- "fmt"
- "os"
- "path/filepath"
-)
-
+ import (
+ "fmt"
+ "os"
+ "path/filepath"
+)
@@ -72,12 +70,11 @@ time.
- func check(e error) {
- if e != nil {
- panic(e)
- }
-}
-
+ func check(e error) {
+ if e != nil {
+ panic(e)
+ }
+}
@@ -87,8 +84,7 @@ time.
- func main() {
-
+ func main() {
@@ -103,10 +99,8 @@ create the file in the default location for our OS.
-
- f, err := os.CreateTemp("", "sample")
- check(err)
-
+ f, err := os.CreateTemp("", "sample")
+ check(err)
@@ -122,9 +116,7 @@ calls will always create different file names.
-
- fmt.Println("Temp file name:", f.Name())
-
+ fmt.Println("Temp file name:", f.Name())
@@ -138,9 +130,7 @@ explicitly.
-
- defer os.Remove(f.Name())
-
+ defer os.Remove(f.Name())
@@ -151,10 +141,8 @@ explicitly.
-
- _, err = f.Write([]byte{1, 2, 3, 4})
- check(err)
-
+ _, err = f.Write([]byte{1, 2, 3, 4})
+ check(err)
@@ -169,11 +157,9 @@ rather than an open file.
-
- dname, err := os.MkdirTemp("", "sampledir")
- check(err)
- fmt.Println("Temp dir name:", dname)
-
+ dname, err := os.MkdirTemp("", "sampledir")
+ check(err)
+ fmt.Println("Temp dir name:", dname)
@@ -183,8 +169,7 @@ rather than an open file.
- defer os.RemoveAll(dname)
-
+ defer os.RemoveAll(dname)
@@ -196,12 +181,10 @@ prefixing them with our temporary directory.
-
- fname := filepath.Join(dname, "file1")
- err = os.WriteFile(fname, []byte{1, 2}, 0666)
- check(err)
-}
-
+ fname := filepath.Join(dname, "file1")
+ err = os.WriteFile(fname, []byte{1, 2}, 0666)
+ check(err)
+}
@@ -215,9 +198,9 @@ prefixing them with our temporary directory.
- $ go run temporary-files-and-directories.go
-Temp file name: /tmp/sample610887201
-Temp dir name: /tmp/sampledir898854668
+ $ go run temporary-files-and-directories.go
+Temp file name: /tmp/sample610887201
+Temp dir name: /tmp/sampledir898854668
diff --git a/public/testing-and-benchmarking b/public/testing-and-benchmarking
index 176b37f..edefa47 100644
--- a/public/testing-and-benchmarking
+++ b/public/testing-and-benchmarking
@@ -48,9 +48,7 @@ typically lives in the same package as the code it tests.

-
-package main
-
+ package main
@@ -60,11 +58,10 @@ typically lives in the same package as the code it tests.
- import (
- "fmt"
- "testing"
-)
-
+ import (
+ "fmt"
+ "testing"
+)
@@ -79,14 +76,12 @@ be named intutils_test.go
.
-
-func IntMin(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
+ func IntMin(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
@@ -98,11 +93,9 @@ beginning with Test
.
-
-func TestIntMinBasic(t *testing.T) {
- ans := IntMin(2, -2)
- if ans != -2 {
-
+ func TestIntMinBasic(t *testing.T) {
+ ans := IntMin(2, -2)
+ if ans != -2 {
@@ -115,11 +108,9 @@ failures and stop the test immediately.
-
- t.Errorf("IntMin(2, -2) = %d; want -2", ans)
- }
-}
-
+ t.Errorf("IntMin(2, -2) = %d; want -2", ans)
+ }
+}
@@ -133,19 +124,17 @@ walks over them and performs the test logic.
-
-func TestIntMinTableDriven(t *testing.T) {
- var tests = []struct {
- a, b int
- want int
- }{
- {0, 1, 0},
- {1, 0, 0},
- {2, -2, -2},
- {0, -1, -1},
- {-1, 0, -1},
- }
-
+ func TestIntMinTableDriven(t *testing.T) {
+ var tests = []struct {
+ a, b int
+ want int
+ }{
+ {0, 1, 0},
+ {1, 0, 0},
+ {2, -2, -2},
+ {0, -1, -1},
+ {-1, 0, -1},
+ }
@@ -158,8 +147,7 @@ when executing go test -v
.
- for _, tt := range tests {
-
+ for _, tt := range tests {
@@ -169,16 +157,15 @@ when executing go test -v
.
- testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
- t.Run(testname, func(t *testing.T) {
- ans := IntMin(tt.a, tt.b)
- if ans != tt.want {
- t.Errorf("got %d, want %d", ans, tt.want)
- }
- })
- }
-}
-
+ testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
+ t.Run(testname, func(t *testing.T) {
+ ans := IntMin(tt.a, tt.b)
+ if ans != tt.want {
+ t.Errorf("got %d, want %d", ans, tt.want)
+ }
+ })
+ }
+}
@@ -192,9 +179,7 @@ executes each benchmark function several times, increasing
-
-func BenchmarkIntMin(b *testing.B) {
-
+ func BenchmarkIntMin(b *testing.B) {
@@ -206,12 +191,10 @@ benchmarking in a loop b.N
times.
-
- for i := 0; i < b.N; i++ {
- IntMin(1, 2)
- }
-}
-
+ for i := 0; i < b.N; i++ {
+ IntMin(1, 2)
+ }
+}
@@ -226,24 +209,23 @@ benchmarking in a loop b.N
times.
-
-$ go test -v
-== RUN TestIntMinBasic
---- PASS: TestIntMinBasic (0.00s)
-=== RUN TestIntMinTableDriven
-=== RUN TestIntMinTableDriven/0,1
-=== RUN TestIntMinTableDriven/1,0
-=== RUN TestIntMinTableDriven/2,-2
-=== RUN TestIntMinTableDriven/0,-1
-=== RUN TestIntMinTableDriven/-1,0
---- PASS: TestIntMinTableDriven (0.00s)
- --- PASS: TestIntMinTableDriven/0,1 (0.00s)
- --- PASS: TestIntMinTableDriven/1,0 (0.00s)
- --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
- --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
- --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
-PASS
-ok examples/testing-and-benchmarking 0.023s
+ $ go test -v
+== RUN TestIntMinBasic
+--- PASS: TestIntMinBasic (0.00s)
+=== RUN TestIntMinTableDriven
+=== RUN TestIntMinTableDriven/0,1
+=== RUN TestIntMinTableDriven/1,0
+=== RUN TestIntMinTableDriven/2,-2
+=== RUN TestIntMinTableDriven/0,-1
+=== RUN TestIntMinTableDriven/-1,0
+--- PASS: TestIntMinTableDriven (0.00s)
+ --- PASS: TestIntMinTableDriven/0,1 (0.00s)
+ --- PASS: TestIntMinTableDriven/1,0 (0.00s)
+ --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
+ --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
+ --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
+PASS
+ok examples/testing-and-benchmarking 0.023s
@@ -256,14 +238,13 @@ benchmark function names with a regexp.
-
-$ go test -bench=.
-goos: darwin
-goarch: arm64
-pkg: examples/testing
-BenchmarkIntMin-8 1000000000 0.3136 ns/op
-PASS
-ok examples/testing-and-benchmarking 0.351s
+ $ go test -bench=.
+goos: darwin
+goarch: arm64
+pkg: examples/testing
+BenchmarkIntMin-8 1000000000 0.3136 ns/op
+PASS
+ok examples/testing-and-benchmarking 0.351s
diff --git a/public/text-templates b/public/text-templates
index df0d536..43b39da 100644
--- a/public/text-templates
+++ b/public/text-templates
@@ -45,8 +45,7 @@ features and should be used for generating HTML.

- package main
-
+ package main
@@ -56,11 +55,10 @@ features and should be used for generating HTML.
- import (
- "os"
- "text/template"
-)
-
+ import (
+ "os"
+ "text/template"
+)
@@ -70,8 +68,7 @@ features and should be used for generating HTML.
- func main() {
-
+ func main() {
@@ -85,13 +82,11 @@ Templates are a mix of static text and “actions” enclosed in
-
- t1 := template.New("t1")
- t1, err := t1.Parse("Value is {{.}}\n")
- if err != nil {
- panic(err)
- }
-
+ t1 := template.New("t1")
+ t1, err := t1.Parse("Value is {{.}}\n")
+ if err != nil {
+ panic(err)
+ }
@@ -104,9 +99,7 @@ useful for templates initialized in the global scope.
-
- t1 = template.Must(t1.Parse("Value: {{.}}\n"))
-
+ t1 = template.Must(t1.Parse("Value: {{.}}\n"))
@@ -119,16 +112,14 @@ replaced by the value passed as a parameter to Execute
.
-
- t1.Execute(os.Stdout, "some text")
- t1.Execute(os.Stdout, 5)
- t1.Execute(os.Stdout, []string{
- "Go",
- "Rust",
- "C++",
- "C#",
- })
-
+ t1.Execute(os.Stdout, "some text")
+ t1.Execute(os.Stdout, 5)
+ t1.Execute(os.Stdout, []string{
+ "Go",
+ "Rust",
+ "C++",
+ "C#",
+ })
@@ -139,11 +130,9 @@ replaced by the value passed as a parameter to Execute
.
-
- Create := func(name, t string) *template.Template {
- return template.Must(template.New(name).Parse(t))
- }
-
+ Create := func(name, t string) *template.Template {
+ return template.Must(template.New(name).Parse(t))
+ }
@@ -156,9 +145,7 @@ template is executing.
-
- t2 := Create("t2", "Name: {{.Name}}\n")
-
+ t2 := Create("t2", "Name: {{.Name}}\n")
@@ -168,10 +155,9 @@ template is executing.
- t2.Execute(os.Stdout, struct {
- Name string
- }{"Jane Doe"})
-
+ t2.Execute(os.Stdout, struct {
+ Name string
+ }{"Jane Doe"})
@@ -183,11 +169,9 @@ case of key names.
-
- t2.Execute(os.Stdout, map[string]string{
- "Name": "Mickey Mouse",
- })
-
+ t2.Execute(os.Stdout, map[string]string{
+ "Name": "Mickey Mouse",
+ })
@@ -202,12 +186,10 @@ feature of templates: using -
in actions to trim whitespace.
-
- t3 := Create("t3",
- "{{if . -}} yes {{else -}} no {{end}}\n")
- t3.Execute(os.Stdout, "not empty")
- t3.Execute(os.Stdout, "")
-
+ t3 := Create("t3",
+ "{{if . -}} yes {{else -}} no {{end}}\n")
+ t3.Execute(os.Stdout, "not empty")
+ t3.Execute(os.Stdout, "")
@@ -219,18 +201,16 @@ the range block {{.}}
is set to the current item of the iteration.<
-
- t4 := Create("t4",
- "Range: {{range .}}{{.}} {{end}}\n")
- t4.Execute(os.Stdout,
- []string{
- "Go",
- "Rust",
- "C++",
- "C#",
- })
-}
-
+ t4 := Create("t4",
+ "Range: {{range .}}{{.}} {{end}}\n")
+ t4.Execute(os.Stdout,
+ []string{
+ "Go",
+ "Rust",
+ "C++",
+ "C#",
+ })
+}
@@ -244,15 +224,15 @@ the range block {{.}}
is set to the current item of the iteration.<
- $ go run templates.go
-Value: some text
-Value: 5
-Value: [Go Rust C++ C#]
-Name: Jane Doe
-Name: Mickey Mouse
-yes
-no
-Range: Go Rust C++ C#
+ $ go run templates.go
+Value: some text
+Value: 5
+Value: [Go Rust C++ C#]
+Name: Jane Doe
+Name: Mickey Mouse
+yes
+no
+Range: Go Rust C++ C#
diff --git a/public/tickers b/public/tickers
index 97ca3b5..f370225 100644
--- a/public/tickers
+++ b/public/tickers
@@ -46,8 +46,7 @@ periodically until we stop it.

- package main
-
+ package main
@@ -57,11 +56,10 @@ periodically until we stop it.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -71,8 +69,7 @@ periodically until we stop it.
- func main() {
-
+ func main() {
@@ -86,10 +83,8 @@ values as they arrive every 500ms.
-
- ticker := time.NewTicker(500 * time.Millisecond)
- done := make(chan bool)
-
+ ticker := time.NewTicker(500 * time.Millisecond)
+ done := make(chan bool)
@@ -99,17 +94,16 @@ values as they arrive every 500ms.
- go func() {
- for {
- select {
- case <-done:
- return
- case t := <-ticker.C:
- fmt.Println("Tick at", t)
- }
- }
- }()
-
+ go func() {
+ for {
+ select {
+ case <-done:
+ return
+ case t := <-ticker.C:
+ fmt.Println("Tick at", t)
+ }
+ }
+ }()
@@ -122,13 +116,11 @@ channel. We’ll stop ours after 1600ms.
-
- time.Sleep(1600 * time.Millisecond)
- ticker.Stop()
- done <- true
- fmt.Println("Ticker stopped")
-}
-
+ time.Sleep(1600 * time.Millisecond)
+ ticker.Stop()
+ done <- true
+ fmt.Println("Ticker stopped")
+}
@@ -144,12 +136,11 @@ before we stop it.
-
-$ go run tickers.go
-Tick at 2012-09-23 11:29:56.487625 -0700 PDT
-Tick at 2012-09-23 11:29:56.988063 -0700 PDT
-Tick at 2012-09-23 11:29:57.488076 -0700 PDT
-Ticker stopped
+ $ go run tickers.go
+Tick at 2012-09-23 11:29:56.487625 -0700 PDT
+Tick at 2012-09-23 11:29:56.988063 -0700 PDT
+Tick at 2012-09-23 11:29:57.488076 -0700 PDT
+Ticker stopped
diff --git a/public/time b/public/time
index c8a2d52..7b46e75 100644
--- a/public/time
+++ b/public/time
@@ -43,8 +43,7 @@ here are some examples.

- package main
-
+ package main
@@ -54,11 +53,10 @@ here are some examples.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -68,9 +66,8 @@ here are some examples.
- func main() {
- p := fmt.Println
-
+ func main() {
+ p := fmt.Println
@@ -81,10 +78,8 @@ here are some examples.
-
- now := time.Now()
- p(now)
-
+ now := time.Now()
+ p(now)
@@ -97,11 +92,9 @@ with a Location
, i.e. time zone.
-
- then := time.Date(
- 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
- p(then)
-
+ then := time.Date(
+ 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
+ p(then)
@@ -113,16 +106,14 @@ value as expected.
-
- p(then.Year())
- p(then.Month())
- p(then.Day())
- p(then.Hour())
- p(then.Minute())
- p(then.Second())
- p(then.Nanosecond())
- p(then.Location())
-
+ p(then.Year())
+ p(then.Month())
+ p(then.Day())
+ p(then.Hour())
+ p(then.Minute())
+ p(then.Second())
+ p(then.Nanosecond())
+ p(then.Location())
@@ -133,9 +124,7 @@ value as expected.
-
- p(then.Weekday())
-
+ p(then.Weekday())
@@ -148,11 +137,9 @@ as the second, respectively.
-
- p(then.Before(now))
- p(then.After(now))
- p(then.Equal(now))
-
+ p(then.Before(now))
+ p(then.After(now))
+ p(then.Equal(now))
@@ -164,10 +151,8 @@ the interval between two times.
-
- diff := now.Sub(then)
- p(diff)
-
+ diff := now.Sub(then)
+ p(diff)
@@ -179,12 +164,10 @@ various units.
-
- p(diff.Hours())
- p(diff.Minutes())
- p(diff.Seconds())
- p(diff.Nanoseconds())
-
+ p(diff.Hours())
+ p(diff.Minutes())
+ p(diff.Seconds())
+ p(diff.Nanoseconds())
@@ -197,11 +180,9 @@ duration.
-
- p(then.Add(diff))
- p(then.Add(-diff))
-}
-
+ p(then.Add(diff))
+ p(then.Add(-diff))
+}
@@ -215,28 +196,28 @@ duration.
- $ go run time.go
-2012-10-31 15:50:13.793654 +0000 UTC
-2009-11-17 20:34:58.651387237 +0000 UTC
-2009
-November
-17
-20
-34
-58
-651387237
-UTC
-Tuesday
-true
-false
-false
-25891h15m15.142266763s
-25891.25420618521
-1.5534752523711128e+06
-9.320851514226677e+07
-93208515142266763
-2012-10-31 15:50:13.793654 +0000 UTC
-2006-12-05 01:19:43.509120474 +0000 UTC
+ $ go run time.go
+2012-10-31 15:50:13.793654 +0000 UTC
+2009-11-17 20:34:58.651387237 +0000 UTC
+2009
+November
+17
+20
+34
+58
+651387237
+UTC
+Tuesday
+true
+false
+false
+25891h15m15.142266763s
+25891.25420618521
+1.5534752523711128e+06
+9.320851514226677e+07
+93208515142266763
+2012-10-31 15:50:13.793654 +0000 UTC
+2006-12-05 01:19:43.509120474 +0000 UTC
diff --git a/public/time-formatting-parsing b/public/time-formatting-parsing
index 7999890..a82af48 100644
--- a/public/time-formatting-parsing
+++ b/public/time-formatting-parsing
@@ -43,8 +43,7 @@ pattern-based layouts.

- package main
-
+ package main
@@ -54,11 +53,10 @@ pattern-based layouts.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -68,9 +66,8 @@ pattern-based layouts.
- func main() {
- p := fmt.Println
-
+ func main() {
+ p := fmt.Println
@@ -83,10 +80,8 @@ constant.
-
- t := time.Now()
- p(t.Format(time.RFC3339))
-
+ t := time.Now()
+ p(t.Format(time.RFC3339))
@@ -97,12 +92,10 @@ constant.
-
- t1, e := time.Parse(
- time.RFC3339,
- "2012-11-01T22:08:41+00:00")
- p(t1)
-
+ t1, e := time.Parse(
+ time.RFC3339,
+ "2012-11-01T22:08:41+00:00")
+ p(t1)
@@ -119,14 +112,12 @@ The example time must be exactly as shown: the year 2006,
-
- p(t.Format("3:04PM"))
- p(t.Format("Mon Jan _2 15:04:05 2006"))
- p(t.Format("2006-01-02T15:04:05.999999-07:00"))
- form := "3 04 PM"
- t2, e := time.Parse(form, "8 41 PM")
- p(t2)
-
+ p(t.Format("3:04PM"))
+ p(t.Format("Mon Jan _2 15:04:05 2006"))
+ p(t.Format("2006-01-02T15:04:05.999999-07:00"))
+ form := "3 04 PM"
+ t2, e := time.Parse(form, "8 41 PM")
+ p(t2)
@@ -139,11 +130,9 @@ components of the time value.
-
- fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
- t.Year(), t.Month(), t.Day(),
- t.Hour(), t.Minute(), t.Second())
-
+ fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
+ t.Year(), t.Month(), t.Day(),
+ t.Hour(), t.Minute(), t.Second())
@@ -155,12 +144,10 @@ explaining the parsing problem.
-
- ansic := "Mon Jan _2 15:04:05 2006"
- _, e = time.Parse(ansic, "8:41PM")
- p(e)
-}
-
+ ansic := "Mon Jan _2 15:04:05 2006"
+ _, e = time.Parse(ansic, "8:41PM")
+ p(e)
+}
@@ -174,15 +161,15 @@ explaining the parsing problem.
- $ go run time-formatting-parsing.go
-2014-04-15T18:00:15-07:00
-2012-11-01 22:08:41 +0000 +0000
-6:00PM
-Tue Apr 15 18:00:15 2014
-2014-04-15T18:00:15.161182-07:00
-0000-01-01 20:41:00 +0000 UTC
-2014-04-15T18:00:15-00:00
-parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": ...
+ $ go run time-formatting-parsing.go
+2014-04-15T18:00:15-07:00
+2012-11-01 22:08:41 +0000 +0000
+6:00PM
+Tue Apr 15 18:00:15 2014
+2014-04-15T18:00:15.161182-07:00
+0000-01-01 20:41:00 +0000 UTC
+2014-04-15T18:00:15-00:00
+parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": ...
diff --git a/public/timeouts b/public/timeouts
index db72edf..39e2ffd 100644
--- a/public/timeouts
+++ b/public/timeouts
@@ -45,8 +45,7 @@ elegant thanks to channels and select
.

- package main
-
+ package main
@@ -56,11 +55,10 @@ elegant thanks to channels and select
.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -70,8 +68,7 @@ elegant thanks to channels and select
.
- func main() {
-
+ func main() {
@@ -87,13 +84,11 @@ channel is never read.
-
- c1 := make(chan string, 1)
- go func() {
- time.Sleep(2 * time.Second)
- c1 <- "result 1"
- }()
-
+ c1 := make(chan string, 1)
+ go func() {
+ time.Sleep(2 * time.Second)
+ c1 <- "result 1"
+ }()
@@ -109,14 +104,12 @@ if the operation takes more than the allowed 1s.
-
- select {
- case res := <-c1:
- fmt.Println(res)
- case <-time.After(1 * time.Second):
- fmt.Println("timeout 1")
- }
-
+ select {
+ case res := <-c1:
+ fmt.Println(res)
+ case <-time.After(1 * time.Second):
+ fmt.Println("timeout 1")
+ }
@@ -128,20 +121,18 @@ from c2
will succeed and we’ll print the result.
-
- c2 := make(chan string, 1)
- go func() {
- time.Sleep(2 * time.Second)
- c2 <- "result 2"
- }()
- select {
- case res := <-c2:
- fmt.Println(res)
- case <-time.After(3 * time.Second):
- fmt.Println("timeout 2")
- }
-}
-
+ c2 := make(chan string, 1)
+ go func() {
+ time.Sleep(2 * time.Second)
+ c2 <- "result 2"
+ }()
+ select {
+ case res := <-c2:
+ fmt.Println(res)
+ case <-time.After(3 * time.Second):
+ fmt.Println("timeout 2")
+ }
+}
@@ -157,10 +148,9 @@ out and the second succeeding.
-
-$ go run timeouts.go
-timeout 1
-result 2
+ $ go run timeouts.go
+timeout 1
+result 2
diff --git a/public/timers b/public/timers
index 2f1f1c9..107d915 100644
--- a/public/timers
+++ b/public/timers
@@ -46,8 +46,7 @@ at tickers.

- package main
-
+ package main
@@ -57,11 +56,10 @@ at tickers.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -71,8 +69,7 @@ at tickers.
- func main() {
-
+ func main() {
@@ -86,9 +83,7 @@ time. This timer will wait 2 seconds.
-
- timer1 := time.NewTimer(2 * time.Second)
-
+ timer1 := time.NewTimer(2 * time.Second)
@@ -101,10 +96,8 @@ fired.
-
- <-timer1.C
- fmt.Println("Timer 1 fired")
-
+ <-timer1.C
+ fmt.Println("Timer 1 fired")
@@ -118,17 +111,15 @@ Here’s an example of that.
-
- timer2 := time.NewTimer(time.Second)
- go func() {
- <-timer2.C
- fmt.Println("Timer 2 fired")
- }()
- stop2 := timer2.Stop()
- if stop2 {
- fmt.Println("Timer 2 stopped")
- }
-
+ timer2 := time.NewTimer(time.Second)
+ go func() {
+ <-timer2.C
+ fmt.Println("Timer 2 fired")
+ }()
+ stop2 := timer2.Stop()
+ if stop2 {
+ fmt.Println("Timer 2 stopped")
+ }
@@ -140,10 +131,8 @@ was going to, to show it is in fact stopped.
-
- time.Sleep(2 * time.Second)
-}
-
+ time.Sleep(2 * time.Second)
+}
@@ -160,10 +149,9 @@ a chance to fire.
-
-$ go run timers.go
-Timer 1 fired
-Timer 2 stopped
+ $ go run timers.go
+Timer 1 fired
+Timer 2 stopped
diff --git a/public/url-parsing b/public/url-parsing
index 61989e4..4b6bc03 100644
--- a/public/url-parsing
+++ b/public/url-parsing
@@ -43,8 +43,7 @@ Here’s how to parse URLs in Go.

- package main
-
+ package main
@@ -54,12 +53,11 @@ Here’s how to parse URLs in Go.
- import (
- "fmt"
- "net"
- "net/url"
-)
-
+ import (
+ "fmt"
+ "net"
+ "net/url"
+)
@@ -69,8 +67,7 @@ Here’s how to parse URLs in Go.
- func main() {
-
+ func main() {
@@ -83,9 +80,7 @@ query params, and query fragment.
-
- s := "postgres://user:pass@host.com:5432/path?k=v#f"
-
+ s := "postgres://user:pass@host.com:5432/path?k=v#f"
@@ -96,12 +91,10 @@ query params, and query fragment.
-
- u, err := url.Parse(s)
- if err != nil {
- panic(err)
- }
-
+ u, err := url.Parse(s)
+ if err != nil {
+ panic(err)
+ }
@@ -112,9 +105,7 @@ query params, and query fragment.
-
- fmt.Println(u.Scheme)
-
+ fmt.Println(u.Scheme)
@@ -127,12 +118,10 @@ values.
-
- fmt.Println(u.User)
- fmt.Println(u.User.Username())
- p, _ := u.User.Password()
- fmt.Println(p)
-
+ fmt.Println(u.User)
+ fmt.Println(u.User.Username())
+ p, _ := u.User.Password()
+ fmt.Println(p)
@@ -144,12 +133,10 @@ if present. Use SplitHostPort
to extract them.
-
- fmt.Println(u.Host)
- host, port, _ := net.SplitHostPort(u.Host)
- fmt.Println(host)
- fmt.Println(port)
-
+ fmt.Println(u.Host)
+ host, port, _ := net.SplitHostPort(u.Host)
+ fmt.Println(host)
+ fmt.Println(port)
@@ -161,10 +148,8 @@ the #
.
-
- fmt.Println(u.Path)
- fmt.Println(u.Fragment)
-
+ fmt.Println(u.Path)
+ fmt.Println(u.Fragment)
@@ -179,13 +164,11 @@ if you only want the first value.
-
- fmt.Println(u.RawQuery)
- m, _ := url.ParseQuery(u.RawQuery)
- fmt.Println(m)
- fmt.Println(m["k"][0])
-}
-
+ fmt.Println(u.RawQuery)
+ m, _ := url.ParseQuery(u.RawQuery)
+ fmt.Println(m)
+ fmt.Println(m["k"][0])
+}
@@ -201,20 +184,19 @@ pieces that we extracted.
-
-$ go run url-parsing.go
-postgres
-user:pass
-user
-pass
-host.com:5432
-host.com
-5432
-/path
-f
-k=v
-map[k:[v]]
-v
+ $ go run url-parsing.go
+postgres
+user:pass
+user
+pass
+host.com:5432
+host.com
+5432
+/path
+f
+k=v
+map[k:[v]]
+v
diff --git a/public/values b/public/values
index 1f04b37..6aece1b 100644
--- a/public/values
+++ b/public/values
@@ -44,8 +44,7 @@ basic examples.

- package main
-
+ package main
@@ -55,8 +54,7 @@ basic examples.
- import "fmt"
-
+ import "fmt"
@@ -66,8 +64,7 @@ basic examples.
- func main() {
-
+ func main() {
@@ -78,9 +75,7 @@ basic examples.
-
- fmt.Println("go" + "lang")
-
+ fmt.Println("go" + "lang")
@@ -91,10 +86,8 @@ basic examples.
-
- fmt.Println("1+1 =", 1+1)
- fmt.Println("7.0/3.0 =", 7.0/3.0)
-
+ fmt.Println("1+1 =", 1+1)
+ fmt.Println("7.0/3.0 =", 7.0/3.0)
@@ -105,12 +98,10 @@ basic examples.
-
- fmt.Println(true && false)
- fmt.Println(true || false)
- fmt.Println(!true)
-}
-
+ fmt.Println(true && false)
+ fmt.Println(true || false)
+ fmt.Println(!true)
+}
@@ -124,13 +115,13 @@ basic examples.
- $ go run values.go
-golang
-1+1 = 2
-7.0/3.0 = 2.3333333333333335
-false
-true
-false
+ $ go run values.go
+golang
+1+1 = 2
+7.0/3.0 = 2.3333333333333335
+false
+true
+false
diff --git a/public/variables b/public/variables
index 11c6fee..5c07db6 100644
--- a/public/variables
+++ b/public/variables
@@ -44,8 +44,7 @@ calls.

- package main
-
+ package main
@@ -55,8 +54,7 @@ calls.
- import "fmt"
-
+ import "fmt"
@@ -66,8 +64,7 @@ calls.
- func main() {
-
+ func main() {
@@ -78,10 +75,8 @@ calls.
-
- var a = "initial"
- fmt.Println(a)
-
+ var a = "initial"
+ fmt.Println(a)
@@ -92,10 +87,8 @@ calls.
-
- var b, c int = 1, 2
- fmt.Println(b, c)
-
+ var b, c int = 1, 2
+ fmt.Println(b, c)
@@ -106,10 +99,8 @@ calls.
-
- var d = true
- fmt.Println(d)
-
+ var d = true
+ fmt.Println(d)
@@ -122,10 +113,8 @@ zero value for an int
is 0
.
-
- var e int
- fmt.Println(e)
-
+ var e int
+ fmt.Println(e)
@@ -139,11 +128,9 @@ This syntax is only available inside functions.
-
- f := "apple"
- fmt.Println(f)
-}
-
+ f := "apple"
+ fmt.Println(f)
+}
@@ -157,12 +144,12 @@ This syntax is only available inside functions.
- $ go run variables.go
-initial
-1 2
-true
-0
-apple
+ $ go run variables.go
+initial
+1 2
+true
+0
+apple
diff --git a/public/variadic-functions b/public/variadic-functions
index 8b86793..a07a44b 100644
--- a/public/variadic-functions
+++ b/public/variadic-functions
@@ -45,8 +45,7 @@ function.

- package main
-
+ package main
@@ -56,8 +55,7 @@ function.
- import "fmt"
-
+ import "fmt"
@@ -69,11 +67,9 @@ of int
s as arguments.
-
-func sum(nums ...int) {
- fmt.Print(nums, " ")
- total := 0
-
+ func sum(nums ...int) {
+ fmt.Print(nums, " ")
+ total := 0
@@ -86,13 +82,11 @@ iterate over it with range
, etc.
-
- for _, num := range nums {
- total += num
- }
- fmt.Println(total)
-}
-
+ for _, num := range nums {
+ total += num
+ }
+ fmt.Println(total)
+}
@@ -102,8 +96,7 @@ iterate over it with range
, etc.
- func main() {
-
+ func main() {
@@ -115,10 +108,8 @@ with individual arguments.
-
- sum(1, 2)
- sum(1, 2, 3)
-
+ sum(1, 2)
+ sum(1, 2, 3)
@@ -131,11 +122,9 @@ apply them to a variadic function using
-
- nums := []int{1, 2, 3, 4}
- sum(nums...)
-}
-
+ nums := []int{1, 2, 3, 4}
+ sum(nums...)
+}
@@ -149,10 +138,10 @@ apply them to a variadic function using
- $ go run variadic-functions.go
-[1 2] 3
-[1 2 3] 6
-[1 2 3 4] 10
+ $ go run variadic-functions.go
+[1 2] 3
+[1 2 3] 6
+[1 2 3 4] 10
diff --git a/public/waitgroups b/public/waitgroups
index 38870e6..6b4465f 100644
--- a/public/waitgroups
+++ b/public/waitgroups
@@ -43,8 +43,7 @@ use a wait group.

- package main
-
+ package main
@@ -54,12 +53,11 @@ use a wait group.
- import (
- "fmt"
- "sync"
- "time"
-)
-
+ import (
+ "fmt"
+ "sync"
+ "time"
+)
@@ -70,10 +68,8 @@ use a wait group.
-
-func worker(id int) {
- fmt.Printf("Worker %d starting\n", id)
-
+ func worker(id int) {
+ fmt.Printf("Worker %d starting\n", id)
@@ -84,11 +80,9 @@ use a wait group.
-
- time.Sleep(time.Second)
- fmt.Printf("Worker %d done\n", id)
-}
-
+ time.Sleep(time.Second)
+ fmt.Printf("Worker %d done\n", id)
+}
@@ -98,8 +92,7 @@ use a wait group.
- func main() {
-
+ func main() {
@@ -112,9 +105,7 @@ explicitly passed into functions, it should be done by pointer.
-
- var wg sync.WaitGroup
-
+ var wg sync.WaitGroup
@@ -126,10 +117,8 @@ counter for each.
-
- for i := 1; i <= 5; i++ {
- wg.Add(1)
-
+ for i := 1; i <= 5; i++ {
+ wg.Add(1)
@@ -142,9 +131,7 @@ for more details.
-
- i := i
-
+ i := i
@@ -158,13 +145,11 @@ involved in its execution.
-
- go func() {
- defer wg.Done()
- worker(i)
- }()
- }
-
+ go func() {
+ defer wg.Done()
+ worker(i)
+ }()
+ }
@@ -176,9 +161,7 @@ all the workers notified they’re done.
-
- wg.Wait()
-
+ wg.Wait()
@@ -192,9 +175,7 @@ advanced use cases, consider using the
-
-}
-
+ }
@@ -208,17 +189,17 @@ advanced use cases, consider using the
- $ go run waitgroups.go
-Worker 5 starting
-Worker 3 starting
-Worker 4 starting
-Worker 1 starting
-Worker 2 starting
-Worker 4 done
-Worker 1 done
-Worker 2 done
-Worker 5 done
-Worker 3 done
+ $ go run waitgroups.go
+Worker 5 starting
+Worker 3 starting
+Worker 4 starting
+Worker 1 starting
+Worker 2 starting
+Worker 4 done
+Worker 1 done
+Worker 2 done
+Worker 5 done
+Worker 3 done
diff --git a/public/worker-pools b/public/worker-pools
index 601a84f..2a024a7 100644
--- a/public/worker-pools
+++ b/public/worker-pools
@@ -43,8 +43,7 @@ a worker pool using goroutines and channels.

- package main
-
+ package main
@@ -54,11 +53,10 @@ a worker pool using goroutines and channels.
- import (
- "fmt"
- "time"
-)
-
+ import (
+ "fmt"
+ "time"
+)
@@ -73,16 +71,14 @@ simulate an expensive task.
-
-func worker(id int, jobs <-chan int, results chan<- int) {
- for j := range jobs {
- fmt.Println("worker", id, "started job", j)
- time.Sleep(time.Second)
- fmt.Println("worker", id, "finished job", j)
- results <- j * 2
- }
-}
-
+ func worker(id int, jobs <-chan int, results chan<- int) {
+ for j := range jobs {
+ fmt.Println("worker", id, "started job", j)
+ time.Sleep(time.Second)
+ fmt.Println("worker", id, "finished job", j)
+ results <- j * 2
+ }
+}
@@ -92,8 +88,7 @@ simulate an expensive task.
- func main() {
-
+ func main() {
@@ -106,11 +101,9 @@ channels for this.
-
- const numJobs = 5
- jobs := make(chan int, numJobs)
- results := make(chan int, numJobs)
-
+ const numJobs = 5
+ jobs := make(chan int, numJobs)
+ results := make(chan int, numJobs)
@@ -122,11 +115,9 @@ because there are no jobs yet.
-
- for w := 1; w <= 3; w++ {
- go worker(w, jobs, results)
- }
-
+ for w := 1; w <= 3; w++ {
+ go worker(w, jobs, results)
+ }
@@ -138,12 +129,10 @@ channel to indicate that’s all the work we have.
-
- for j := 1; j <= numJobs; j++ {
- jobs <- j
- }
- close(jobs)
-
+ for j := 1; j <= numJobs; j++ {
+ jobs <- j
+ }
+ close(jobs)
@@ -157,12 +146,10 @@ goroutines is to use a WaitGroup.
-
- for a := 1; a <= numJobs; a++ {
- <-results
- }
-}
-
+ for a := 1; a <= numJobs; a++ {
+ <-results
+ }
+}
@@ -180,18 +167,17 @@ there are 3 workers operating concurrently.
-
-$ time go run worker-pools.go
-worker 1 started job 1
-worker 2 started job 2
-worker 3 started job 3
-worker 1 finished job 1
-worker 1 started job 4
-worker 2 finished job 2
-worker 2 started job 5
-worker 3 finished job 3
-worker 1 finished job 4
-worker 2 finished job 5
+ $ time go run worker-pools.go
+worker 1 started job 1
+worker 2 started job 2
+worker 3 started job 3
+worker 1 finished job 1
+worker 1 started job 4
+worker 2 finished job 2
+worker 2 started job 5
+worker 3 finished job 3
+worker 1 finished job 4
+worker 2 finished job 5
@@ -201,7 +187,7 @@ there are 3 workers operating concurrently.
- real 0m2.358s
+ real 0m2.358s
diff --git a/public/writing-files b/public/writing-files
index c9864b0..75ef522 100644
--- a/public/writing-files
+++ b/public/writing-files
@@ -43,8 +43,7 @@ ones we saw earlier for reading.

- package main
-
+ package main
@@ -54,12 +53,11 @@ ones we saw earlier for reading.
- import (
- "bufio"
- "fmt"
- "os"
-)
-
+ import (
+ "bufio"
+ "fmt"
+ "os"
+)
@@ -69,12 +67,11 @@ ones we saw earlier for reading.
- func check(e error) {
- if e != nil {
- panic(e)
- }
-}
-
+ func check(e error) {
+ if e != nil {
+ panic(e)
+ }
+}
@@ -84,8 +81,7 @@ ones we saw earlier for reading.
- func main() {
-
+ func main() {
@@ -97,11 +93,9 @@ bytes) into a file.
-
- d1 := []byte("hello\ngo\n")
- err := os.WriteFile("/tmp/dat1", d1, 0644)
- check(err)
-
+ d1 := []byte("hello\ngo\n")
+ err := os.WriteFile("/tmp/dat1", d1, 0644)
+ check(err)
@@ -112,10 +106,8 @@ bytes) into a file.
-
- f, err := os.Create("/tmp/dat2")
- check(err)
-
+ f, err := os.Create("/tmp/dat2")
+ check(err)
@@ -127,9 +119,7 @@ after opening a file.
-
- defer f.Close()
-
+ defer f.Close()
@@ -140,12 +130,10 @@ after opening a file.
-
- d2 := []byte{115, 111, 109, 101, 10}
- n2, err := f.Write(d2)
- check(err)
- fmt.Printf("wrote %d bytes\n", n2)
-
+ d2 := []byte{115, 111, 109, 101, 10}
+ n2, err := f.Write(d2)
+ check(err)
+ fmt.Printf("wrote %d bytes\n", n2)
@@ -156,11 +144,9 @@ after opening a file.
-
- n3, err := f.WriteString("writes\n")
- check(err)
- fmt.Printf("wrote %d bytes\n", n3)
-
+ n3, err := f.WriteString("writes\n")
+ check(err)
+ fmt.Printf("wrote %d bytes\n", n3)
@@ -171,9 +157,7 @@ after opening a file.
-
- f.Sync()
-
+ f.Sync()
@@ -185,12 +169,10 @@ to the buffered readers we saw earlier.
-
- w := bufio.NewWriter(f)
- n4, err := w.WriteString("buffered\n")
- check(err)
- fmt.Printf("wrote %d bytes\n", n4)
-
+ w := bufio.NewWriter(f)
+ n4, err := w.WriteString("buffered\n")
+ check(err)
+ fmt.Printf("wrote %d bytes\n", n4)
@@ -202,9 +184,7 @@ been applied to the underlying writer.
-
- w.Flush()
-
+ w.Flush()
@@ -214,8 +194,7 @@ been applied to the underlying writer.
- }
-
+ }
@@ -230,11 +209,10 @@ been applied to the underlying writer.
-
-$ go run writing-files.go
-wrote 5 bytes
-wrote 7 bytes
-wrote 9 bytes
+ $ go run writing-files.go
+wrote 5 bytes
+wrote 7 bytes
+wrote 9 bytes
@@ -245,14 +223,13 @@ been applied to the underlying writer.
-
-$ cat /tmp/dat1
-hello
-go
-$ cat /tmp/dat2
-some
-writes
-buffered
+ $ cat /tmp/dat1
+hello
+go
+$ cat /tmp/dat2
+some
+writes
+buffered
diff --git a/public/xml b/public/xml
index 26752fe..5ea737a 100644
--- a/public/xml
+++ b/public/xml
@@ -43,8 +43,7 @@ formats with the encoding.xml
package.

- package main
-
+ package main
@@ -54,11 +53,10 @@ formats with the encoding.xml
package.
- import (
- "encoding/xml"
- "fmt"
-)
-
+ import (
+ "encoding/xml"
+ "fmt"
+)
@@ -75,14 +73,12 @@ the name of the XML element representing this struct;
-
-type Plant struct {
- XMLName xml.Name `xml:"plant"`
- Id int `xml:"id,attr"`
- Name string `xml:"name"`
- Origin []string `xml:"origin"`
-}
-
+ type Plant struct {
+ XMLName xml.Name `xml:"plant"`
+ Id int `xml:"id,attr"`
+ Name string `xml:"name"`
+ Origin []string `xml:"origin"`
+}
@@ -92,11 +88,10 @@ the name of the XML element representing this struct;
- func (p Plant) String() string {
- return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
- p.Id, p.Name, p.Origin)
-}
-
+ func (p Plant) String() string {
+ return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
+ p.Id, p.Name, p.Origin)
+}
@@ -106,10 +101,9 @@ the name of the XML element representing this struct;
- func main() {
- coffee := &Plant{Id: 27, Name: "Coffee"}
- coffee.Origin = []string{"Ethiopia", "Brazil"}
-
+ func main() {
+ coffee := &Plant{Id: 27, Name: "Coffee"}
+ coffee.Origin = []string{"Ethiopia", "Brazil"}
@@ -122,10 +116,8 @@ human-readable output.
-
- out, _ := xml.MarshalIndent(coffee, " ", " ")
- fmt.Println(string(out))
-
+ out, _ := xml.MarshalIndent(coffee, " ", " ")
+ fmt.Println(string(out))
@@ -137,9 +129,7 @@ it explicitly.
-
- fmt.Println(xml.Header + string(out))
-
+ fmt.Println(xml.Header + string(out))
@@ -153,13 +143,11 @@ will be returned.
-
- var p Plant
- if err := xml.Unmarshal(out, &p); err != nil {
- panic(err)
- }
- fmt.Println(p)
-
+ var p Plant
+ if err := xml.Unmarshal(out, &p); err != nil {
+ panic(err)
+ }
+ fmt.Println(p)
@@ -169,9 +157,8 @@ will be returned.
- tomato := &Plant{Id: 81, Name: "Tomato"}
- tomato.Origin = []string{"Mexico", "California"}
-
+ tomato := &Plant{Id: 81, Name: "Tomato"}
+ tomato.Origin = []string{"Mexico", "California"}
@@ -183,12 +170,10 @@ to nest all plant
s under <parent><child>...
-
- type Nesting struct {
- XMLName xml.Name `xml:"nesting"`
- Plants []*Plant `xml:"parent>child>plant"`
- }
-
+ type Nesting struct {
+ XMLName xml.Name `xml:"nesting"`
+ Plants []*Plant `xml:"parent>child>plant"`
+ }
@@ -198,9 +183,8 @@ to nest all plant
s under <parent><child>...
- nesting := &Nesting{}
- nesting.Plants = []*Plant{coffee, tomato}
-
+ nesting := &Nesting{}
+ nesting.Plants = []*Plant{coffee, tomato}
@@ -210,10 +194,9 @@ to nest all plant
s under <parent><child>...
- out, _ = xml.MarshalIndent(nesting, " ", " ")
- fmt.Println(string(out))
-}
-
+ out, _ = xml.MarshalIndent(nesting, " ", " ")
+ fmt.Println(string(out))
+}
@@ -227,35 +210,35 @@ to nest all plant
s under <parent><child>...
- $ go run xml.go
- <plant id="27">
- <name>Coffee</name>
- <origin>Ethiopia</origin>
- <origin>Brazil</origin>
- </plant>
-<?xml version="1.0" encoding="UTF-8"?>
- <plant id="27">
- <name>Coffee</name>
- <origin>Ethiopia</origin>
- <origin>Brazil</origin>
- </plant>
-Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
- <nesting>
- <parent>
- <child>
- <plant id="27">
- <name>Coffee</name>
- <origin>Ethiopia</origin>
- <origin>Brazil</origin>
- </plant>
- <plant id="81">
- <name>Tomato</name>
- <origin>Mexico</origin>
- <origin>California</origin>
- </plant>
- </child>
- </parent>
- </nesting>
+ $ go run xml.go
+ <plant id="27">
+ <name>Coffee</name>
+ <origin>Ethiopia</origin>
+ <origin>Brazil</origin>
+ </plant>
+<?xml version="1.0" encoding="UTF-8"?>
+ <plant id="27">
+ <name>Coffee</name>
+ <origin>Ethiopia</origin>
+ <origin>Brazil</origin>
+ </plant>
+Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
+ <nesting>
+ <parent>
+ <child>
+ <plant id="27">
+ <name>Coffee</name>
+ <origin>Ethiopia</origin>
+ <origin>Brazil</origin>
+ </plant>
+ <plant id="81">
+ <name>Tomato</name>
+ <origin>Mexico</origin>
+ <origin>California</origin>
+ </plant>
+ </child>
+ </parent>
+ </nesting>
diff --git a/tools/generate.go b/tools/generate.go
index 9362c74..bc6935e 100644
--- a/tools/generate.go
+++ b/tools/generate.go
@@ -12,10 +12,10 @@ import (
"strings"
"text/template"
- "github.com/alecthomas/chroma"
- "github.com/alecthomas/chroma/formatters/html"
- "github.com/alecthomas/chroma/lexers"
- "github.com/alecthomas/chroma/styles"
+ "github.com/alecthomas/chroma/v2"
+ "github.com/alecthomas/chroma/v2/formatters/html"
+ "github.com/alecthomas/chroma/v2/lexers"
+ "github.com/alecthomas/chroma/v2/styles"
"github.com/russross/blackfriday/v2"
)
@@ -222,6 +222,12 @@ func parseAndRenderSegs(sourcePath string) ([]*Seg, string) {
seg.DocsRendered = markdown(seg.Docs)
}
if seg.Code != "" {
+ // TODO: with the update to Chroma 2.8.0 I had to change this, because the
+ // new chromoa would render this leading newline for all code segments,
+ // which would then be shifted down compared to the doc segments. Maybe
+ // the parsing should be modified to not produce this \n in the first
+ // place?
+ seg.Code = strings.TrimLeft(seg.Code, "\n")
seg.CodeRendered = chromaFormat(seg.Code, sourcePath)
// adding the content to the js code for copying to the clipboard
@@ -353,30 +359,32 @@ var SimpleShellOutputLexer = chroma.MustNewLexer(
Filenames: []string{"*.sh"},
MimeTypes: []string{},
},
- chroma.Rules{
- "root": {
- // $ or > triggers the start of prompt formatting
- {`^\$`, chroma.GenericPrompt, chroma.Push("prompt")},
- {`^>`, chroma.GenericPrompt, chroma.Push("prompt")},
+ func() chroma.Rules {
+ return chroma.Rules{
+ "root": {
+ // $ or > triggers the start of prompt formatting
+ {`^\$`, chroma.GenericPrompt, chroma.Push("prompt")},
+ {`^>`, chroma.GenericPrompt, chroma.Push("prompt")},
- // empty lines are just text
- {`^$\n`, chroma.Text, nil},
+ // empty lines are just text
+ {`^$\n`, chroma.Text, nil},
- // otherwise its all output
- {`[^\n]+$\n?`, chroma.GenericOutput, nil},
- },
- "prompt": {
- // when we find newline, do output formatting rules
- {`\n`, chroma.Text, chroma.Push("output")},
- // otherwise its all text
- {`[^\n]+$`, chroma.Text, nil},
- },
- "output": {
- // sometimes there isn't output so we go right back to prompt
- {`^\$`, chroma.GenericPrompt, chroma.Pop(1)},
- {`^>`, chroma.GenericPrompt, chroma.Pop(1)},
- // otherwise its all output
- {`[^\n]+$\n?`, chroma.GenericOutput, nil},
- },
+ // otherwise its all output
+ {`[^\n]+$\n?`, chroma.GenericOutput, nil},
+ },
+ "prompt": {
+ // when we find newline, do output formatting rules
+ {`\n`, chroma.Text, chroma.Push("output")},
+ // otherwise its all text
+ {`[^\n]+$`, chroma.Text, nil},
+ },
+ "output": {
+ // sometimes there isn't output so we go right back to prompt
+ {`^\$`, chroma.GenericPrompt, chroma.Pop(1)},
+ {`^>`, chroma.GenericPrompt, chroma.Pop(1)},
+ // otherwise its all output
+ {`[^\n]+$\n?`, chroma.GenericOutput, nil},
+ },
+ }
},
)