diff --git a/go.mod b/go.mod index 08c82c0..1f29711 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/mmcgrana/gobyexample go 1.21 require ( - github.com/alecthomas/chroma v0.8.2 + github.com/alecthomas/chroma/v2 v2.8.0 github.com/aws/aws-sdk-go-v2 v1.9.0 github.com/aws/aws-sdk-go-v2/config v1.7.0 github.com/aws/aws-sdk-go-v2/service/s3 v1.14.0 @@ -20,6 +20,5 @@ require ( github.com/aws/aws-sdk-go-v2/service/sso v1.4.0 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 // indirect github.com/aws/smithy-go v1.8.0 // indirect - github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect - github.com/dlclark/regexp2 v1.2.0 // indirect + github.com/dlclark/regexp2 v1.10.0 // indirect ) diff --git a/go.sum b/go.sum index a395d87..4917b64 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,9 @@ -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U= -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= -github.com/alecthomas/chroma v0.8.2 h1:x3zkuE2lUk/RIekyAJ3XRqSCP4zwWDfcw/YJCuCAACg= -github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 h1:JHZL0hZKJ1VENNfmXvHbgYlbUOvpzYzvy2aZU5gXVeo= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= -github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= +github.com/alecthomas/assert/v2 v2.2.1 h1:XivOgYcduV98QCahG8T5XTezV5bylXe+lBxLG2K2ink= +github.com/alecthomas/assert/v2 v2.2.1/go.mod h1:pXcQ2Asjp247dahGEmsZ6ru0UVwnkhktn7S0bBDLxvQ= +github.com/alecthomas/chroma/v2 v2.8.0 h1:w9WJUjFFmHHB2e8mRpL9jjy3alYDlU0QLDezj1xE264= +github.com/alecthomas/chroma/v2 v2.8.0/go.mod h1:yrkMI9807G1ROx13fhe1v6PN2DDeaR73L3d+1nmYQtw= +github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= +github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/aws/aws-sdk-go-v2 v1.9.0 h1:+S+dSqQCN3MSU5vJRu1HqHrq00cJn6heIMU7X9hcsoo= github.com/aws/aws-sdk-go-v2 v1.9.0/go.mod h1:cK/D0BBs0b/oWPIcX/Z/obahJK1TT7IPVjy53i/mX/4= github.com/aws/aws-sdk-go-v2/config v1.7.0 h1:J2cZ7qe+3IpqBEXnHUrFrOjoB9BlsXg7j53vxcl5IVg= @@ -31,34 +28,20 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.7.0 h1:1at4e5P+lvHNl2nUktdM2/v+rpICg github.com/aws/aws-sdk-go-v2/service/sts v1.7.0/go.mod h1:0qcSMCyASQPN2sk/1KQLQ2Fh6yq8wm0HSDAimPhzCoM= github.com/aws/smithy-go v1.8.0 h1:AEwwwXQZtUwP5Mz506FeXXrKBe0jA8gVM+1gEcSRooc= github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= -github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= -github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0= +github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200413165638-669c56c373c4 h1:opSr2sbRXk5X5/givKrrKj9HXxFpW2sdCiP8MJSKLQY= -golang.org/x/sys v0.0.0-20200413165638-669c56c373c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/public/arrays b/public/arrays index b333813..675a3f3 100644 --- a/public/arrays +++ b/public/arrays @@ -45,8 +45,7 @@ scenarios.

-
package main
-
+
package main
@@ -56,8 +55,7 @@ scenarios.

-
import "fmt"
-
+
import "fmt"
@@ -67,8 +65,7 @@ scenarios.

-
func main() {
-
+
func main() {
@@ -82,10 +79,8 @@ zero-valued, which for ints means 0s.

-
-    var a [5]int
-    fmt.Println("emp:", a)
-
+
    var a [5]int
+    fmt.Println("emp:", a)
@@ -98,11 +93,9 @@ zero-valued, which for ints means 0s.

-
-    a[4] = 100
-    fmt.Println("set:", a)
-    fmt.Println("get:", a[4])
-
+
    a[4] = 100
+    fmt.Println("set:", a)
+    fmt.Println("get:", a[4])
@@ -113,9 +106,7 @@ zero-valued, which for ints means 0s.

-
-    fmt.Println("len:", len(a))
-
+
    fmt.Println("len:", len(a))
@@ -127,10 +118,8 @@ in one line.

-
-    b := [5]int{1, 2, 3, 4, 5}
-    fmt.Println("dcl:", b)
-
+
    b := [5]int{1, 2, 3, 4, 5}
+    fmt.Println("dcl:", b)
@@ -143,16 +132,14 @@ structures.

-
-    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)
+}
@@ -168,14 +155,13 @@ when printed with 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]]
diff --git a/public/atomic-counters b/public/atomic-counters index 6548101..fccef50 100644 --- a/public/atomic-counters +++ b/public/atomic-counters @@ -47,8 +47,7 @@ counters accessed by multiple goroutines.

-
package main
-
+
package main
@@ -58,12 +57,11 @@ counters accessed by multiple goroutines.

-
import (
-    "fmt"
-    "sync"
-    "sync/atomic"
-)
-
+
import (
+    "fmt"
+    "sync"
+    "sync/atomic"
+)
@@ -73,8 +71,7 @@ counters accessed by multiple goroutines.

-
func main() {
-
+
func main() {
@@ -86,9 +83,7 @@ counters accessed by multiple goroutines.

-
-    var ops uint64
-
+
    var ops uint64
@@ -100,9 +95,7 @@ to finish their work.

-
-    var wg sync.WaitGroup
-
+
    var wg sync.WaitGroup
@@ -114,10 +107,8 @@ counter exactly 1000 times.

-
-    for i := 0; i < 50; i++ {
-        wg.Add(1)
-
+
    for i := 0; i < 50; i++ {
+        wg.Add(1)
@@ -131,9 +122,8 @@ address of our ops counter with the -
        go func() {
-            for c := 0; c < 1000; c++ {
-
+
        go func() {
+            for c := 0; c < 1000; c++ {
@@ -143,12 +133,11 @@ address of our ops counter with the -
                atomic.AddUint64(&ops, 1)
-            }
-            wg.Done()
-        }()
-    }
-
+
                atomic.AddUint64(&ops, 1)
+            }
+            wg.Done()
+        }()
+    }
@@ -159,9 +148,7 @@ address of our ops counter with the -
-    wg.Wait()
-
+
    wg.Wait()
@@ -176,10 +163,8 @@ also possible, using functions like -
-    fmt.Println("ops:", ops)
-}
-
+
    fmt.Println("ops:", ops)
+}
@@ -199,9 +184,8 @@ when running with the -race flag.

-
-$ go run atomic-counters.go
-ops: 50000
+
$ go run atomic-counters.go
+ops: 50000
diff --git a/public/base64-encoding b/public/base64-encoding index c2db003..94812e2 100644 --- a/public/base64-encoding +++ b/public/base64-encoding @@ -43,8 +43,7 @@ encoding/decoding.

-
package main
-
+
package main
@@ -57,12 +56,10 @@ save us some space below.

-
-import (
-    b64 "encoding/base64"
-    "fmt"
-)
-
+
import (
+    b64 "encoding/base64"
+    "fmt"
+)
@@ -72,8 +69,7 @@ save us some space below.

-
func main() {
-
+
func main() {
@@ -84,9 +80,7 @@ save us some space below.

-
-    data := "abc123!?$*&()'-=@~"
-
+
    data := "abc123!?$*&()'-=@~"
@@ -100,10 +94,8 @@ convert our string to that type.

-
-    sEnc := b64.StdEncoding.EncodeToString([]byte(data))
-    fmt.Println(sEnc)
-
+
    sEnc := b64.StdEncoding.EncodeToString([]byte(data))
+    fmt.Println(sEnc)
@@ -116,11 +108,9 @@ well-formed.

-
-    sDec, _ := b64.StdEncoding.DecodeString(sEnc)
-    fmt.Println(string(sDec))
-    fmt.Println()
-
+
    sDec, _ := b64.StdEncoding.DecodeString(sEnc)
+    fmt.Println(string(sDec))
+    fmt.Println()
@@ -132,13 +122,11 @@ format.

-
-    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))
+}
@@ -155,10 +143,9 @@ but they both decode to the original string as desired.

-
-$ go run base64-encoding.go
-YWJjMTIzIT8kKiYoKSctPUB+
-abc123!?$*&()'-=@~
+
$ go run base64-encoding.go
+YWJjMTIzIT8kKiYoKSctPUB+
+abc123!?$*&()'-=@~
@@ -168,8 +155,8 @@ but they both decode to the original string as desired.

-
YWJjMTIzIT8kKiYoKSctPUB-
-abc123!?$*&()'-=@~
+
YWJjMTIzIT8kKiYoKSctPUB-
+abc123!?$*&()'-=@~
diff --git a/public/channel-buffering b/public/channel-buffering index 3975022..bbac79d 100644 --- a/public/channel-buffering +++ b/public/channel-buffering @@ -47,8 +47,7 @@ those values.

-
package main
-
+
package main
@@ -58,8 +57,7 @@ those values.

-
import "fmt"
-
+
import "fmt"
@@ -69,8 +67,7 @@ those values.

-
func main() {
-
+
func main() {
@@ -82,9 +79,7 @@ those values.

-
-    messages := make(chan string, 2)
-
+
    messages := make(chan string, 2)
@@ -97,10 +92,8 @@ concurrent receive.

-
-    messages <- "buffered"
-    messages <- "channel"
-
+
    messages <- "buffered"
+    messages <- "channel"
@@ -111,11 +104,9 @@ concurrent receive.

-
-    fmt.Println(<-messages)
-    fmt.Println(<-messages)
-}
-
+
    fmt.Println(<-messages)
+    fmt.Println(<-messages)
+}
@@ -129,9 +120,9 @@ concurrent receive.

-
$ go run channel-buffering.go 
-buffered
-channel
+
$ go run channel-buffering.go 
+buffered
+channel
diff --git a/public/channel-directions b/public/channel-directions index 5695a28..2f554f9 100644 --- a/public/channel-directions +++ b/public/channel-directions @@ -45,8 +45,7 @@ the program.

-
package main
-
+
package main
@@ -56,8 +55,7 @@ the program.

-
import "fmt"
-
+
import "fmt"
@@ -70,11 +68,9 @@ receive on this channel.

-
-func ping(pings chan<- string, msg string) {
-    pings <- msg
-}
-
+
func ping(pings chan<- string, msg string) {
+    pings <- msg
+}
@@ -86,12 +82,10 @@ receive on this channel.

-
-func pong(pings <-chan string, pongs chan<- string) {
-    msg := <-pings
-    pongs <- msg
-}
-
+
func pong(pings <-chan string, pongs chan<- string) {
+    msg := <-pings
+    pongs <- msg
+}
@@ -101,14 +95,13 @@ receive on this channel.

-
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)
+}
@@ -122,8 +115,8 @@ receive on this channel.

-
$ go run channel-directions.go
-passed message
+
$ go run channel-directions.go
+passed message
diff --git a/public/channel-synchronization b/public/channel-synchronization index 9061590..f9ce950 100644 --- a/public/channel-synchronization +++ b/public/channel-synchronization @@ -46,8 +46,7 @@ you may prefer to use a WaitGroup.

-
package main
-
+
package main
@@ -57,11 +56,10 @@ you may prefer to use a WaitGroup.

-
import (
-    "fmt"
-    "time"
-)
-
+
import (
+    "fmt"
+    "time"
+)
@@ -74,12 +72,10 @@ goroutine that this function’s work is done.

-
-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")
@@ -90,10 +86,8 @@ goroutine that this function’s work is done.

-
-    done <- true
-}
-
+
    done <- true
+}
@@ -103,8 +97,7 @@ goroutine that this function’s work is done.

-
func main() {
-
+
func main() {
@@ -116,10 +109,8 @@ notify on.

-
-    done := make(chan bool, 1)
-    go worker(done)
-
+
    done := make(chan bool, 1)
+    go worker(done)
@@ -131,10 +122,8 @@ worker on the channel.

-
-    <-done
-}
-
+
    <-done
+}
@@ -148,8 +137,8 @@ worker on the channel.

-
$ go run channel-synchronization.go      
-working...done                  
+
$ go run channel-synchronization.go      
+working...done                  
diff --git a/public/channels b/public/channels index 3b161a7..2ad6de0 100644 --- a/public/channels +++ b/public/channels @@ -45,8 +45,7 @@ goroutine.

-
package main
-
+
package main
@@ -56,8 +55,7 @@ goroutine.

-
import "fmt"
-
+
import "fmt"
@@ -67,8 +65,7 @@ goroutine.

-
func main() {
-
+
func main() {
@@ -80,9 +77,7 @@ Channels are typed by the values they convey.

-
-    messages := make(chan string)
-
+
    messages := make(chan string)
@@ -95,9 +90,7 @@ channel we made above, from a new goroutine.

-
-    go func() { messages <- "ping" }()
-
+
    go func() { messages <- "ping" }()
@@ -110,11 +103,9 @@ we sent above and print it out.

-
-    msg := <-messages
-    fmt.Println(msg)
-}
-
+
    msg := <-messages
+    fmt.Println(msg)
+}
@@ -131,9 +122,8 @@ our channel.

-
-$ go run channels.go 
-ping
+
$ go run channels.go 
+ping
diff --git a/public/closing-channels b/public/closing-channels index d1fad4f..a631097 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -44,8 +44,7 @@ completion to the channel’s receivers.

-
package main
-
+
package main
@@ -55,8 +54,7 @@ completion to the channel’s receivers.

-
import "fmt"
-
+
import "fmt"
@@ -70,11 +68,9 @@ the worker we’ll 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)
@@ -91,20 +87,18 @@ all our jobs.

-
-    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
+            }
+        }
+    }()
@@ -116,14 +110,12 @@ channel, then closes it.

-
-    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")
@@ -136,10 +128,8 @@ we saw earlier.

-
-    <-done
-}
-
+
    <-done
+}
@@ -153,15 +143,15 @@ we saw earlier.

-
$ 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
diff --git a/public/closures b/public/closures index 8b8edd0..399acd3 100644 --- a/public/closures +++ b/public/closures @@ -45,8 +45,7 @@ a function inline without having to name it.

-
package main
-
+
package main
@@ -56,8 +55,7 @@ a function inline without having to name it.

-
import "fmt"
-
+
import "fmt"
@@ -71,15 +69,13 @@ form a closure.

-
-func intSeq() func() int {
-    i := 0
-    return func() int {
-        i++
-        return i
-    }
-}
-
+
func intSeq() func() int {
+    i := 0
+    return func() int {
+        i++
+        return i
+    }
+}
@@ -89,8 +85,7 @@ form a closure.

-
func main() {
-
+
func main() {
@@ -104,9 +99,7 @@ we call nextInt.

-
-    nextInt := intSeq()
-
+
    nextInt := intSeq()
@@ -118,11 +111,9 @@ a few times.

-
-    fmt.Println(nextInt())
-    fmt.Println(nextInt())
-    fmt.Println(nextInt())
-
+
    fmt.Println(nextInt())
+    fmt.Println(nextInt())
+    fmt.Println(nextInt())
@@ -134,11 +125,9 @@ particular function, create and test a new one.

-
-    newInts := intSeq()
-    fmt.Println(newInts())
-}
-
+
    newInts := intSeq()
+    fmt.Println(newInts())
+}
@@ -152,11 +141,11 @@ particular function, create and test a new one.

-
$ go run closures.go
-1
-2
-3
-1
+
$ go run closures.go
+1
+2
+3
+1
diff --git a/public/command-line-arguments b/public/command-line-arguments index b0d5322..132a57d 100644 --- a/public/command-line-arguments +++ b/public/command-line-arguments @@ -45,8 +45,7 @@ For example, go run hello.go uses run and -
package main
-
+
package main
@@ -56,11 +55,10 @@ For example, go run hello.go uses run and -
import (
-    "fmt"
-    "os"
-)
-
+
import (
+    "fmt"
+    "os"
+)
@@ -70,8 +68,7 @@ For example, go run hello.go uses run and -
func main() {
-
+
func main() {
@@ -85,10 +82,8 @@ holds the arguments to the program.

-
-    argsWithProg := os.Args
-    argsWithoutProg := os.Args[1:]
-
+
    argsWithProg := os.Args
+    argsWithoutProg := os.Args[1:]
@@ -99,9 +94,7 @@ holds the arguments to the program.

-
-    arg := os.Args[3]
-
+
    arg := os.Args[3]
@@ -111,11 +104,10 @@ holds the arguments to the program.

-
    fmt.Println(argsWithProg)
-    fmt.Println(argsWithoutProg)
-    fmt.Println(arg)
-}
-
+
    fmt.Println(argsWithProg)
+    fmt.Println(argsWithoutProg)
+    fmt.Println(arg)
+}
@@ -131,12 +123,11 @@ build a binary with 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
diff --git a/public/command-line-flags b/public/command-line-flags index 92e2f2e..e58d909 100644 --- a/public/command-line-flags +++ b/public/command-line-flags @@ -45,8 +45,7 @@ command-line flag.

-
package main
-
+
package main
@@ -59,12 +58,10 @@ implement our example command-line program.

-
-import (
-    "flag"
-    "fmt"
-)
-
+
import (
+    "flag"
+    "fmt"
+)
@@ -74,8 +71,7 @@ implement our example command-line program.

-
func main() {
-
+
func main() {
@@ -91,9 +87,7 @@ we’ll see how to use this pointer below.

-
-    wordPtr := flag.String("word", "foo", "a string")
-
+
    wordPtr := flag.String("word", "foo", "a string")
@@ -105,10 +99,8 @@ similar approach to the 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")
@@ -122,10 +114,8 @@ declaration function.

-
-    var svar string
-    flag.StringVar(&svar, "svar", "bar", "a string var")
-
+
    var svar string
+    flag.StringVar(&svar, "svar", "bar", "a string var")
@@ -137,9 +127,7 @@ to execute the command-line parsing.

-
-    flag.Parse()
-
+
    flag.Parse()
@@ -153,14 +141,12 @@ to get the actual option values.

-
-    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())
+}
@@ -177,8 +163,7 @@ binary directly.

-
-$ go build command-line-flags.go
+
$ go build command-line-flags.go
@@ -190,13 +175,12 @@ all flags.

-
-$ ./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: []
@@ -208,13 +192,12 @@ their default values.

-
-$ ./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: []
@@ -226,11 +209,10 @@ any flags.

-
-$ ./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]
@@ -243,13 +225,12 @@ will be interpreted as positional arguments).

-
-$ ./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]
@@ -261,13 +242,12 @@ generated help text for the command-line program.

-
-$ ./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
@@ -280,11 +260,10 @@ and show the help text again.

-
-$ ./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:
+...
diff --git a/public/command-line-subcommands b/public/command-line-subcommands index 9ea0cba..cc95b27 100644 --- a/public/command-line-subcommands +++ b/public/command-line-subcommands @@ -47,8 +47,7 @@ subcommands that have their own flags.

-
package main
-
+
package main
@@ -58,12 +57,11 @@ subcommands that have their own flags.

-
import (
-    "flag"
-    "fmt"
-    "os"
-)
-
+
import (
+    "flag"
+    "fmt"
+    "os"
+)
@@ -73,8 +71,7 @@ subcommands that have their own flags.

-
func main() {
-
+
func main() {
@@ -87,11 +84,9 @@ for this subcommand.

-
-    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")
@@ -103,10 +98,8 @@ supported flags.

-
-    barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
-    barLevel := barCmd.Int("level", 0, "level")
-
+
    barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
+    barLevel := barCmd.Int("level", 0, "level")
@@ -118,12 +111,10 @@ to the program.

-
-    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)
+    }
@@ -134,9 +125,7 @@ to the program.

-
-    switch os.Args[1] {
-
+
    switch os.Args[1] {
@@ -148,24 +137,22 @@ have access to trailing positional arguments.

-
-    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)
+    }
+}
@@ -179,7 +166,7 @@ have access to trailing positional arguments.

-
$ go build command-line-subcommands.go 
+
$ go build command-line-subcommands.go 
@@ -190,12 +177,11 @@ have access to trailing positional arguments.

-
-$ ./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]
@@ -206,11 +192,10 @@ have access to trailing positional arguments.

-
-$ ./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]
@@ -221,12 +206,11 @@ have access to trailing positional arguments.

-
-$ ./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
diff --git a/public/constants b/public/constants index 0188473..1a5e56a 100644 --- a/public/constants +++ b/public/constants @@ -43,8 +43,7 @@ and numeric values.

-
package main
-
+
package main
@@ -54,11 +53,10 @@ and numeric values.

-
import (
-    "fmt"
-    "math"
-)
-
+
import (
+    "fmt"
+    "math"
+)
@@ -69,9 +67,7 @@ and numeric values.

-
-const s string = "constant"
-
+
const s string = "constant"
@@ -81,9 +77,8 @@ and numeric values.

-
func main() {
-    fmt.Println(s)
-
+
func main() {
+    fmt.Println(s)
@@ -95,9 +90,7 @@ statement can.

-
-    const n = 500000000
-
+
    const n = 500000000
@@ -109,10 +102,8 @@ arbitrary precision.

-
-    const d = 3e20 / n
-    fmt.Println(d)
-
+
    const d = 3e20 / n
+    fmt.Println(d)
@@ -124,9 +115,7 @@ one, such as by an explicit conversion.

-
-    fmt.Println(int64(d))
-
+
    fmt.Println(int64(d))
@@ -140,10 +129,8 @@ assignment or function call. For example, here -
-    fmt.Println(math.Sin(n))
-}
-
+
    fmt.Println(math.Sin(n))
+}
@@ -157,11 +144,11 @@ assignment or function call. For example, here -
$ go run constant.go 
-constant
-6e+11
-600000000000
--0.28470407323754404
+
$ go run constant.go 
+constant
+6e+11
+600000000000
+-0.28470407323754404
diff --git a/public/context b/public/context index 576162f..c60472d 100644 --- a/public/context +++ b/public/context @@ -37,9 +37,7 @@ across API boundaries and goroutines.

-
-package main
-
+
package main
@@ -49,12 +47,11 @@ across API boundaries and goroutines.

-
import (
-    "fmt"
-    "net/http"
-    "time"
-)
-
+
import (
+    "fmt"
+    "net/http"
+    "time"
+)
@@ -64,8 +61,7 @@ across API boundaries and goroutines.

-
func hello(w http.ResponseWriter, req *http.Request) {
-
+
func hello(w http.ResponseWriter, req *http.Request) {
@@ -78,11 +74,9 @@ the 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")
@@ -97,12 +91,10 @@ the work and return as soon as possible.

-
-    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():
@@ -115,14 +107,12 @@ closed.

-
-        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)
+    }
+}
@@ -132,8 +122,7 @@ closed.

-
func main() {
-
+
func main() {
@@ -145,11 +134,9 @@ route, and start serving.

-
-    http.HandleFunc("/hello", hello)
-    http.ListenAndServe(":8090", nil)
-}
-
+
    http.HandleFunc("/hello", hello)
+    http.ListenAndServe(":8090", nil)
+}
@@ -164,8 +151,7 @@ route, and start serving.

-
-$ go run context-in-http-servers.go &
+
$ go run context-in-http-servers.go &
@@ -178,12 +164,11 @@ cancellation.

-
-$ 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
diff --git a/public/defer b/public/defer index 2e48c9e..84cb13f 100644 --- a/public/defer +++ b/public/defer @@ -45,8 +45,7 @@ purposes of cleanup. defer is often used where e.g. -
package main
-
+
package main
@@ -56,11 +55,10 @@ purposes of cleanup. defer is often used where e.g. -
import (
-    "fmt"
-    "os"
-)
-
+
import (
+    "fmt"
+    "os"
+)
@@ -73,9 +71,7 @@ do that with defer.

-
-func main() {
-
+
func main() {
@@ -90,12 +86,10 @@ of the enclosing function (main), after -
-    f := createFile("/tmp/defer.txt")
-    defer closeFile(f)
-    writeFile(f)
-}
-
+
    f := createFile("/tmp/defer.txt")
+    defer closeFile(f)
+    writeFile(f)
+}
@@ -105,15 +99,14 @@ of the enclosing function (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
+}
@@ -123,10 +116,9 @@ of the enclosing function (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")
@@ -136,8 +128,7 @@ of the enclosing function (main), after -
}
-
+
}
@@ -149,10 +140,9 @@ file, even in a deferred function.

-
func closeFile(f *os.File) {
-    fmt.Println("closing")
-    err := f.Close()
-
+
func closeFile(f *os.File) {
+    fmt.Println("closing")
+    err := f.Close()
@@ -162,12 +152,11 @@ file, even in a deferred function.

-
    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)
+    }
+}
@@ -183,11 +172,10 @@ after being written.

-
-$ go run defer.go
-creating
-writing
-closing
+
$ go run defer.go
+creating
+writing
+closing
diff --git a/public/directories b/public/directories index bef7856..5dfbd60 100644 --- a/public/directories +++ b/public/directories @@ -43,8 +43,7 @@ -
package main
-
+
package main
@@ -54,12 +53,11 @@ -
import (
-    "fmt"
-    "os"
-    "path/filepath"
-)
-
+
import (
+    "fmt"
+    "os"
+    "path/filepath"
+)
@@ -69,12 +67,11 @@ -
func check(e error) {
-    if e != nil {
-        panic(e)
-    }
-}
-
+
func check(e error) {
+    if e != nil {
+        panic(e)
+    }
+}
@@ -84,8 +81,7 @@ -
func main() {
-
+
func main() {
@@ -97,10 +93,8 @@ directory.

-
-    err := os.Mkdir("subdir", 0755)
-    check(err)
-
+
    err := os.Mkdir("subdir", 0755)
+    check(err)
@@ -114,9 +108,7 @@ will delete a whole directory tree (similarly to -
-    defer os.RemoveAll("subdir")
-
+
    defer os.RemoveAll("subdir")
@@ -127,12 +119,10 @@ will delete a whole directory tree (similarly to -
-    createEmptyFile := func(name string) {
-        d := []byte("")
-        check(os.WriteFile(name, d, 0644))
-    }
-
+
    createEmptyFile := func(name string) {
+        d := []byte("")
+        check(os.WriteFile(name, d, 0644))
+    }
@@ -142,8 +132,7 @@ will delete a whole directory tree (similarly to -
    createEmptyFile("subdir/file1")
-
+
    createEmptyFile("subdir/file1")
@@ -156,10 +145,8 @@ command-line mkdir -p.

-
-    err = os.MkdirAll("subdir/parent/child", 0755)
-    check(err)
-
+
    err = os.MkdirAll("subdir/parent/child", 0755)
+    check(err)
@@ -169,10 +156,9 @@ command-line 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")
@@ -184,10 +170,8 @@ slice of os.DirEntry objects.

-
-    c, err := os.ReadDir("subdir/parent")
-    check(err)
-
+
    c, err := os.ReadDir("subdir/parent")
+    check(err)
@@ -197,11 +181,10 @@ slice of 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())
+    }
@@ -213,10 +196,8 @@ similarly to cd.

-
-    err = os.Chdir("subdir/parent/child")
-    check(err)
-
+
    err = os.Chdir("subdir/parent/child")
+    check(err)
@@ -228,10 +209,8 @@ when listing the current directory.

-
-    c, err = os.ReadDir(".")
-    check(err)
-
+
    c, err = os.ReadDir(".")
+    check(err)
@@ -241,11 +220,10 @@ when listing the current directory.

-
    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())
+    }
@@ -256,10 +234,8 @@ when listing the current directory.

-
-    err = os.Chdir("../../..")
-    check(err)
-
+
    err = os.Chdir("../../..")
+    check(err)
@@ -273,11 +249,9 @@ directory visited.

-
-    fmt.Println("Visiting subdir")
-    err = filepath.Walk("subdir", visit)
-}
-
+
    fmt.Println("Visiting subdir")
+    err = filepath.Walk("subdir", visit)
+}
@@ -289,15 +263,13 @@ recursively by 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
+}
@@ -311,21 +283,21 @@ recursively by 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
diff --git a/public/embed-directive b/public/embed-directive index 906bece..d7d0692 100644 --- a/public/embed-directive +++ b/public/embed-directive @@ -36,9 +36,7 @@ build time. Read more about the embed directive -
-package main
-
+
package main
@@ -50,11 +48,9 @@ identifiers from this package, you can do a blank import with _ "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 rects.

-
-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 rects.

-
-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.Writers 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.Writers 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 ints.

-
-func vals() (int, int) {
-    return 3, 7
-}
-
+
func vals() (int, int) {
+    return 3, 7
+}
@@ -82,8 +78,7 @@ the function returns 2 ints.

-
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 selects.

-
package main
-
+
package main
@@ -56,8 +55,7 @@ non-blocking multi-way selects.

-
import "fmt"
-
+
import "fmt"
@@ -67,10 +65,9 @@ non-blocking multi-way selects.

-
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 Opening 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 Opening with -
-    f.Close()
-}
-
+
    f.Close()
+}
@@ -245,15 +224,15 @@ be scheduled immediately after Opening 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 ints 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 plants 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 plants under <parent><child>... -
    nesting := &Nesting{}
-    nesting.Plants = []*Plant{coffee, tomato}
-
+
    nesting := &Nesting{}
+    nesting.Plants = []*Plant{coffee, tomato}
@@ -210,10 +194,9 @@ to nest all plants 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 plants 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}, + }, + } }, )