### Running WaitGroups Example
Source: https://gobyexample.com/waitgroups
Shows the typical output of the WaitGroups example, demonstrating the interleaved start and completion of worker goroutines.
```bash
$ 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 HTTP Client: Example Output
Source: https://gobyexample.com/http-client
This is the expected output when running the HTTP client example.
```bash
$ go run http-clients.go
Response status: 200 OK
Go by Example
```
--------------------------------
### Create Files for Embed Example
Source: https://gobyexample.com/embed-directive
Commands to set up the necessary directory and files for the embed directive example to work.
```bash
$ mkdir -p folder
$ echo "hello go" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash
```
--------------------------------
### Main Function Start
Source: https://gobyexample.com/embed-directive
The entry point for the Go program.
```go
func main() {
```
--------------------------------
### Go Structs Example Output
Source: https://gobyexample.com/structs
This is the expected output from running the Go structs example.
```text
$ go run structs.go
{Bob 20}
{Alice 30}
{Fred 0}
&{Ann 40}
&{Jon 42}
Sean
50
51
{Rex true}
```
--------------------------------
### Main Function Setup
Source: https://gobyexample.com/interfaces
Initializes 'rect' and 'circle' instances within the main function.
```go
func main() {
r := rect{width: 3, height: 4}
c := circle{radius: 5}
```
--------------------------------
### Main function to start HTTP server
Source: https://gobyexample.com/context
Sets up the HTTP server and registers the hello handler.
```go
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8090", nil)
}
```
--------------------------------
### Set up Worker Pool and Channels in Go
Source: https://gobyexample.com/worker-pools
Initializes the main function, defines the number of jobs, and creates channels for jobs and results. This setup is necessary before starting the worker goroutines.
```go
func main() {
const numJobs = 5
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
```
--------------------------------
### Go Time Example Output
Source: https://gobyexample.com/time
This section shows the expected output when running the Go time example code.
```text
$ 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
```
--------------------------------
### Example Output
Source: https://gobyexample.com/enums
Shows the expected output when running the Go program.
```text
$ go run enums.go
connected
idle
```
--------------------------------
### Go Switch Example Output
Source: https://gobyexample.com/switch
The expected output when running the Go switch statement examples.
```text
$ 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 Basic Timer Example
Source: https://gobyexample.com/timers
Demonstrates creating a timer that fires after a specified duration and receiving its notification.
```go
package main
import (
"fmt"
"time"
)
func main() {
timer1 := time.NewTimer(2 * time.Second)
<-timer1.C
fmt.Println("Timer 1 fired")
timer2 := time.NewTimer(time.Second)
go func() {
<-timer2.C
fmt.Println("Timer 2 fired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Println("Timer 2 stopped")
}
time.Sleep(2 * time.Second)
}
```
--------------------------------
### Start TCP Listener
Source: https://gobyexample.com/tcp-server
Initializes a TCP listener on port 8090, binding to all available network interfaces. Handles potential errors during listener setup.
```go
listener, err := net.Listen("tcp", ":8090")
if err != nil {
log.Fatal("Error listening:", err)
}
```
--------------------------------
### Go JSON Example Output
Source: https://gobyexample.com/json
This section shows the expected output from running the Go JSON example code.
```text
$ 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}
{1 [apple peach]}
```
--------------------------------
### Example execution output
Source: https://gobyexample.com/stateful-goroutines
Shows the typical output of the stateful goroutines example, indicating the number of read and write operations completed.
```bash
$ go run stateful-goroutines.go
readOps: 71708
writeOps: 7177
```
--------------------------------
### Example output of spawning processes
Source: https://gobyexample.com/spawning-processes
Illustrates the typical output when running the Go program that spawns external commands.
```bash
$ go run spawning-processes.go
> date
Thu 05 May 2022 10:10:12 PM PDT
```
```bash
command exit rc = 1
> grep hello
hello grep
```
```bash
> 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
```
--------------------------------
### Example Output
Source: https://gobyexample.com/methods
The output demonstrates calling methods on both value and pointer receiver types.
```text
$ go run methods.go
area: 50
perim: 30
area: 50
perim: 30
```
--------------------------------
### Run Go Channel Example
Source: https://gobyexample.com/channels
Shows the output of the Go channel program, demonstrating successful message passing between goroutines.
```bash
$ go run channels.go
ping
```
--------------------------------
### Example Output for Temporary Files and Directories
Source: https://gobyexample.com/temporary-files-and-directories
This is the expected output when running the Go program that creates temporary files and directories.
```bash
$ go run temporary-files-and-directories.go
Temp file name: /tmp/sample610887201
Temp dir name: /tmp/sampledir898854668
```
--------------------------------
### Epoch Time Output Example
Source: https://gobyexample.com/epoch
This is an example output showing the current time, followed by the epoch time in seconds, milliseconds, and nanoseconds. It also demonstrates converting epoch seconds and nanoseconds back into a human-readable time format.
```bash
$ 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 Generics Example Output
Source: https://gobyexample.com/generics
The expected output when running the Go program demonstrating generics.
```text
$ go run generics.go
index of zoo: 2
list: [10 13 23]
```
--------------------------------
### Go: URL Parsing Example Output
Source: https://gobyexample.com/url-parsing
The output demonstrates the successful extraction of various components from a sample URL.
```text
$ go run url-parsing.go
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
map[k:[v]]
v
```
--------------------------------
### Array Output Example
Source: https://gobyexample.com/arrays
Shows the typical output format of arrays when printed using `fmt.Println` in Go.
```bash
$ 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]
dcl: [1 2 3 4 5]
idx: [100 0 0 400 500]
2d: [[0 1 2] [1 2 3]]
2d: [[1 2 3] [1 2 3]]
```
--------------------------------
### Go Number Parsing Output Example
Source: https://gobyexample.com/number-parsing
This is the expected output when running the Go number parsing example code.
```text
$ go run number-parsing.go
1.234
123
456
789
135
strconv.ParseInt: parsing "wat": invalid syntax
```
--------------------------------
### Example execution and output
Source: https://gobyexample.com/atomic-counters
Shows the command to run the Go program and its expected output, demonstrating the atomic counter's correct value.
```bash
$ go run atomic-counters.go
ops: 50000
```
--------------------------------
### Example execution with Ctrl+C
Source: https://gobyexample.com/signals
Demonstrates running the program and interrupting it with Ctrl+C, showing the signal received and program exit.
```bash
$ go run signals.go
awaiting signal
^C
interrupt signal received
exiting
```
--------------------------------
### Go Text Template Execution Output
Source: https://gobyexample.com/text-templates
Example output from running the Go text template code.
```text
$ 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#
```
--------------------------------
### Example Environment Variable Keys
Source: https://gobyexample.com/environment-variables
Illustrates typical environment variable keys that might be present on a system, including the one set by the program (`FOO`).
```text
TERM_PROGRAM
PATH
SHELL
...
FOO
```
--------------------------------
### Example Output
Source: https://gobyexample.com/directories
The expected output when running the Go program, showing directory listings and recursive traversal results.
```text
$ 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
```
--------------------------------
### Register Handlers and Start HTTP Server
Source: https://gobyexample.com/http-server
Register handler functions to specific routes and start the HTTP server on port 8090.
```go
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers)
http.ListenAndServe(":8090", nil)
}
```
--------------------------------
### Run HTTP Server in Background
Source: https://gobyexample.com/http-server
Execute the Go program to start the HTTP server in the background.
```bash
$ go run http-server.go &
```
--------------------------------
### Example Output: Range over Channels
Source: https://gobyexample.com/range-over-channels
This is the expected output when running the Go program that ranges over a channel.
```text
$ go run range-over-channels.go
one
two
```
--------------------------------
### Go Function Execution Example
Source: https://gobyexample.com/functions
Demonstrates calling defined functions and printing their results using the 'fmt' package. Shows the output of the 'functions.go' program.
```bash
$ go run functions.go
1+2 = 3
1+2+3 = 6
```
--------------------------------
### Recursion Example Output
Source: https://gobyexample.com/recursion
Shows the output of running the Go program that includes both factorial and Fibonacci recursive functions.
```text
$ go run recursion.go
5040
13
```
--------------------------------
### Example Output 1
Source: https://gobyexample.com/strings-and-runes
Shows the expected output when running the Go program, including byte lengths, hex byte values, rune counts, and rune details from a range loop.
```text
$ 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 Timer Execution Output
Source: https://gobyexample.com/timers
Shows the expected output when running the Go timer example code.
```bash
$ go run timers.go
Timer 1 fired
Timer 2 stopped
```
--------------------------------
### Example Output of Select Statement
Source: https://gobyexample.com/select
Shows the expected output when running the Go program, demonstrating the order in which messages are received.
```bash
$ time go run select.go
received one
received two
```
--------------------------------
### Example Output
Source: https://gobyexample.com/mutexes
The expected output shows that the counters were updated correctly by the concurrent goroutines.
```bash
$ go run mutexes.go
map[a:20000 b:10000]
```
--------------------------------
### Go String Functions Example
Source: https://gobyexample.com/string-functions
Demonstrates various functions from the Go `strings` package. Remember that these are package functions, not methods, so the string is passed as the first argument.
```go
package main
```
```go
import (
"fmt"
s "strings"
)
```
```go
var p = fmt.Println
```
```go
func main() {
```
```go
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"))
}
```
--------------------------------
### Output of Closing Channels Example
Source: https://gobyexample.com/closing-channels
Shows the expected output when running the Go program that demonstrates closing channels.
```text
$ 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
received more jobs: false
```
--------------------------------
### Struct Embedding Example Output
Source: https://gobyexample.com/struct-embedding
The output of the Go program demonstrating struct embedding.
```text
$ go run struct-embedding.go
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1
```
--------------------------------
### Execute 'foo' Subcommand
Source: https://gobyexample.com/command-line-subcommands
Example of running the compiled program with the 'foo' subcommand, providing flags and positional arguments.
```bash
./command-line-subcommands foo -enable -name=joe a1 a2
subcommand 'foo'
enable: true
name: joe
tail: [a1 a2]
```
--------------------------------
### Define Struct for Formatting
Source: https://gobyexample.com/string-formatting
Defines a simple struct that will be used in subsequent formatting examples.
```go
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
```
--------------------------------
### Example Execution Output
Source: https://gobyexample.com/writing-files
Shows the expected output when the Go program is run, indicating the number of bytes written by different operations.
```bash
$ go run writing-files.go
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
```
--------------------------------
### Basic Panic Example in Go
Source: https://gobyexample.com/panic
Demonstrates a simple panic to indicate an unexpected problem. This program will exit immediately when the panic occurs.
```go
package main
```
```go
import (
"os"
"path/filepath"
)
```
```go
func main() {
panic("a problem")
}
```
--------------------------------
### Example Output of Environment Variable Program
Source: https://gobyexample.com/environment-variables
Shows the output when running the Go program, illustrating that `FOO` is set internally and `BAR` is retrieved from the environment.
```bash
$ go run environment-variables.go
FOO: 1
BAR:
```
--------------------------------
### Go Sorting by Functions Output
Source: https://gobyexample.com/sorting-by-functions
Example output demonstrating the results of sorting strings by length and structs by age.
```text
$ go run sorting-by-functions.go
[kiwi peach banana]
[{TJ 25} {Jax 37} {Alex 72}]
```
--------------------------------
### Run Embed Directive Example
Source: https://gobyexample.com/embed-directive
Command to run the Go program and expected output, demonstrating the embedded file contents.
```bash
$ go run embed-directive.go
hello go
hello go
123
456
```
--------------------------------
### Building and Running with Arguments
Source: https://gobyexample.com/command-line-arguments
Shows the process of building a Go program and then executing it with sample command-line arguments, displaying the output.
```bash
$ 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
```
--------------------------------
### Return to the original directory
Source: https://gobyexample.com/directories
Changes the current working directory back to the starting point using a relative path.
```go
err = os.Chdir("../../..")
check(err)
```
--------------------------------
### Accessing Command-Line Arguments
Source: https://gobyexample.com/command-line-arguments
Demonstrates how to access all command-line arguments, including the program path, and how to get only the arguments passed to the program. It also shows how to access individual arguments by index.
```go
func main() {
argsWithProg := os.Args
argsWithoutProg := os.Args[1:]
arg := os.Args[3]
fmt.Println(argsWithProg)
fmt.Println(argsWithoutProg)
fmt.Println(arg)
}
```
--------------------------------
### Execute 'bar' Subcommand
Source: https://gobyexample.com/command-line-subcommands
Example of running the compiled program with the 'bar' subcommand, providing flags and positional arguments.
```bash
./command-line-subcommands bar -level 8 a1
subcommand 'bar'
level: 8
tail: [a1]
```
--------------------------------
### Example Output for Non-Blocking Channel Operations
Source: https://gobyexample.com/non-blocking-channel-operations
Shows the expected output when running the Go program demonstrating non-blocking channel operations.
```text
$ go run non-blocking-channel-operations.go
no message received
no message sent
no activity
```
--------------------------------
### Go For Loop Execution Output
Source: https://gobyexample.com/for
This output demonstrates the results of the various for loop examples, showing the printed values for each iteration and loop type.
```text
$ go run for.go
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
```
--------------------------------
### Create and Initialize a Map
Source: https://gobyexample.com/maps
Demonstrates creating an empty map using `make` and populating it with key/value pairs. Also shows direct initialization.
```go
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println("map:", m)
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
```
--------------------------------
### Example XML Output
Source: https://gobyexample.com/xml
This shows the expected output when marshaling and unmarshaling XML data using the defined Go structs.
```text
$ go run xml.go
Coffee
Ethiopia
Brazil
Coffee
Ethiopia
Brazil
Plant id=27, name=Coffee, origin=[Ethiopia Brazil]
Coffee
Ethiopia
Brazil
Tomato
Mexico
California
```
--------------------------------
### Building a Go Executable
Source: https://gobyexample.com/hello-world
Illustrates how to compile a Go program into an executable binary using 'go build' and lists the resulting files.
```bash
$ go build hello-world.go
$ ls
hello-world hello-world.go
```
--------------------------------
### Example Output of Custom Error Handling
Source: https://gobyexample.com/custom-errors
This is the expected output when running the Go program that demonstrates custom error handling.
```text
$ go run custom-errors.go
42
can't work with it
```
--------------------------------
### Launch goroutines for writes
Source: https://gobyexample.com/stateful-goroutines
Starts 10 goroutines that continuously issue write requests to the state-managing goroutine. Each write involves sending a writeOp and receiving a confirmation.
```go
for range 10 {
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)
}
}()
}
```
--------------------------------
### Example Ticker Output
Source: https://gobyexample.com/tickers
Illustrates the expected output when running the Go ticker program, showing ticks and the final stop message.
```bash
$ 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
```
--------------------------------
### Example Goroutine Execution Output
Source: https://gobyexample.com/goroutines
Illustrates the typical output of the program, showing interleaved execution between the direct function call and the launched goroutines.
```bash
$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done
```
--------------------------------
### Main function with Channel Synchronization
Source: https://gobyexample.com/channel-synchronization
The main entry point of the program. It creates a channel, starts a worker goroutine, and blocks until the worker signals completion via the channel.
```go
func main() {
done := make(chan bool, 1)
go worker(done)
<-done
}
```
--------------------------------
### Variadic Function Output Example
Source: https://gobyexample.com/variadic-functions
Shows the expected output when calling the `sum` variadic function with different sets of arguments and an unpacked slice.
```text
$ go run variadic-functions.go
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10
```
--------------------------------
### Go Slice Execution Output
Source: https://gobyexample.com/slices
This is the expected output when running the Go slice example code. It shows the state of slices after various operations.
```text
$ 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]
t == t2
2d: [[0] [1 2] [2 3 4]]
```
--------------------------------
### Split directory and base name
Source: https://gobyexample.com/file-paths
Use `filepath.Dir` to get the directory part of a path and `filepath.Base` to get the file name. `filepath.Split` can also return both.
```go
fmt.Println("Dir(p):", filepath.Dir(p))
```
```go
fmt.Println("Base(p):", filepath.Base(p))
```
--------------------------------
### Executing a Built Go Binary
Source: https://gobyexample.com/hello-world
Demonstrates how to run the compiled executable binary of a Go program.
```bash
$ ./hello-world
hello world
```
--------------------------------
### Example Output 2
Source: https://gobyexample.com/strings-and-runes
Displays the output from the explicit rune decoding section, showing the decoded runes and the results of the `examineRune` function.
```text
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
```
--------------------------------
### List All Environment Variables in Go
Source: https://gobyexample.com/environment-variables
Use `os.Environ` to get a slice of all environment variables as KEY=value strings. You can then split these strings to access keys and values.
```go
fmt.Println()
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
fmt.Println(pair[0])
}
```
--------------------------------
### Go HTTP Client: Make a GET Request
Source: https://gobyexample.com/http-client
Use `http.Get` for simple HTTP GET requests. This function is a shortcut that uses the default client. Ensure to close the response body and handle potential errors.
```go
package main
```
```go
import (
"bufio"
"fmt"
"net/http"
)
```
```go
func main() {
resp, err := http.Get("https://gobyexample.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}
```
--------------------------------
### Get Epoch Time in Go
Source: https://gobyexample.com/epoch
Use `time.Now` with `Unix`, `UnixMilli`, or `UnixNano` to get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds, respectively. This is useful for logging, performance measurement, or any scenario requiring a timestamp.
```go
package main
```
```go
import (
"fmt"
"time"
)
```
```go
func main() {
```
```go
now := time.Now()
fmt.Println(now)
```
```go
fmt.Println(now.Unix())
fmt.Println(now.UnixMilli())
fmt.Println(now.UnixNano())
```
```go
fmt.Println(time.Unix(now.Unix(), 0))
fmt.Println(time.Unix(0, now.UnixNano()))
}
```
--------------------------------
### Go Sorting Output
Source: https://gobyexample.com/sorting
Example output from the Go sorting program, showing sorted strings, integers, and the result of the sorted check.
```bash
$ go run sorting.go
Strings: [a b c]
Ints: [2 4 7]
Sorted: true
```
--------------------------------
### Building and Running Go Binary
Source: https://gobyexample.com/exit
Illustrates building a Go program into an executable binary, running it, and then checking the exit status using `echo $?` in the terminal.
```bash
$ go build exit.go
$ ./exit
$ echo $?
```
--------------------------------
### Example Output of Recover
Source: https://gobyexample.com/recover
Shows the expected output when a panic is successfully recovered.
```text
$ go run recover.go
Recovered. Error:
a problem
```
--------------------------------
### Create and Initialize a Struct in Go
Source: https://gobyexample.com/structs
Demonstrates various ways to create and initialize structs, including direct initialization, named fields, zero-valued fields, and struct pointers.
```go
func main() {
fmt.Println(person{"Bob", 20})
fmt.Println(person{name: "Alice", age: 30})
fmt.Println(person{name: "Fred"})
fmt.Println(&person{name: "Ann", age: 40})
}
```
--------------------------------
### Initialize and populate List
Source: https://gobyexample.com/range-over-iterators
Creates a new List and adds some integer elements to it.
```go
func main() {
lst := List[int]{}
lst.Push(10)
lst.Push(13)
lst.Push(23)
```
--------------------------------
### Set and Get Environment Variables in Go
Source: https://gobyexample.com/environment-variables
Use `os.Setenv` to set environment variables and `os.Getenv` to retrieve them. `os.Getenv` returns an empty string if the variable is not set.
```go
package main
import (
"fmt"
"os"
"strings"
)
func main() {
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
}
```
--------------------------------
### Launch goroutines for reads
Source: https://gobyexample.com/stateful-goroutines
Starts 100 goroutines that continuously issue read requests to the state-managing goroutine. Each read involves sending a readOp and receiving the result.
```go
for range 100 {
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)
}
}()
}
```
--------------------------------
### Panic Output Example in Go
Source: https://gobyexample.com/panic
Illustrates the typical output when a Go program panics, including the panic message, goroutine traces, and exit status. This output helps in debugging unexpected program termination.
```bash
$ go run panic.go
panic: a problem
```
```bash
goroutine 1 [running]:
main.main()
/.../panic.go:12 +0x47
...
exit status 2
```
--------------------------------
### Declare and Initialize an Array
Source: https://gobyexample.com/arrays
Demonstrates creating an array of a specific type and length, initializing it with default zero values, and then setting individual elements.
```go
package main
import "fmt"
func main() {
var a [5]int
fmt.Println("emp:", a)
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
fmt.Println("len:", len(a))
}
```
--------------------------------
### Basic Rate Limiting Output
Source: https://gobyexample.com/rate-limiting
Example output demonstrating requests processed at a fixed interval.
```text
$ 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
```
--------------------------------
### Example SHA256 Hash Output
Source: https://gobyexample.com/sha256-hashes
This is the expected output when running the SHA256 hash computation program.
```bash
$ go run sha256-hashes.go
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...
```
--------------------------------
### Import necessary packages
Source: https://gobyexample.com/file-paths
Import the `fmt`, `path/filepath`, and `strings` packages for path manipulation and printing.
```go
package main
import (
"fmt"
"path/filepath"
"strings"
)
```
--------------------------------
### URL-Compatible Base64 Encoding Output
Source: https://gobyexample.com/base64-encoding
Example output of URL-compatible base64 encoding and decoding. Observe the differences in the encoded string compared to standard base64, particularly the use of '-' instead of '+'.
```text
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
```
--------------------------------
### Basic Unit Test
Source: https://gobyexample.com/testing-and-benchmarking
A basic unit test function for `IntMin`. Test functions must start with `Test`. `t.Error*` reports failures and continues, while `t.Fatal*` stops the test.
```go
func TestIntMinBasic(t *testing.T) {
ans := IntMin(2, -2)
if ans != -2 {
t.Errorf("IntMin(2, -2) = %d; want -2", ans)
}
}
```
--------------------------------
### Get Slice Length in Go
Source: https://gobyexample.com/slices
The `len` function returns the current number of elements in a slice.
```go
fmt.Println("len:", len(s))
```
--------------------------------
### Create and Open File for Writing
Source: https://gobyexample.com/writing-files
Opens a file for writing, creating it if it doesn't exist. It's crucial to defer closing the file immediately after opening.
```go
path2 := filepath.Join(os.TempDir(), "dat2")
f, err := os.Create(path2)
check(err)
```
```go
defer f.Close()
```
--------------------------------
### Get the cause of context cancellation
Source: https://gobyexample.com/signals
Retrieves the reason for the context cancellation. For signal-based cancellations, this will be the signal value.
```go
fmt.Println()
fmt.Println(context.Cause(ctx))
fmt.Println("exiting")
}
```
--------------------------------
### Get Map Length
Source: https://gobyexample.com/maps
Uses the built-in `len` function to determine the number of key/value pairs in a map.
```go
fmt.Println("len:", len(m))
```
--------------------------------
### Initialize and Run Goroutines
Source: https://gobyexample.com/mutexes
Initialize the container and set up a WaitGroup. Define a helper function to increment counters in a loop and launch multiple goroutines to execute this function concurrently.
```go
func main() {
c := Container{
counters: map[string]int{"a": 0, "b": 0},
}
var wg sync.WaitGroup
doIncrement := func(name string, n int) {
for range n {
c.inc(name)
}
}
wg.Go(func() {
doIncrement("a", 10000)
})
wg.Go(func() {
doIncrement("a", 10000)
})
wg.Go(func() {
doIncrement("b", 10000)
})
wg.Wait()
fmt.Println(c.counters)
}
```
--------------------------------
### Build the Go Program
Source: https://gobyexample.com/command-line-subcommands
Compiles the Go source file into an executable binary.
```bash
go build command-line-subcommands.go
```
--------------------------------
### Run a command and capture its output
Source: https://gobyexample.com/spawning-processes
Use `exec.Command` to create a command object and `Output` to run it and capture stdout. Errors during execution or non-zero exit codes are handled.
```go
func main() {
dateCmd := exec.Command("date")
dateOut, err := dateCmd.Output()
if err != nil {
panic(err)
}
fmt.Println("> date")
fmt.Println(string(dateOut))
```
--------------------------------
### Burstable Rate Limiting Output
Source: https://gobyexample.com/rate-limiting
Example output showing initial burst of requests followed by delayed processing.
```text
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
```
--------------------------------
### Import Necessary Packages
Source: https://gobyexample.com/command-line-flags
Import the 'flag' package for flag parsing and 'fmt' for output.
```go
package main
import (
"flag"
"fmt"
)
```
--------------------------------
### Launch an Anonymous Goroutine
Source: https://gobyexample.com/goroutines
Starts a goroutine from an anonymous function literal. This is useful for short, one-off concurrent tasks.
```go
go func(msg string) {
fmt.Println(msg)
}("going")
```
--------------------------------
### Declare and Initialize Array with Values
Source: https://gobyexample.com/arrays
Shows how to declare and initialize an array in a single line. The compiler can also count the number of elements using `...`.
```go
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
b = [...]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
```
--------------------------------
### Remove file extension
Source: https://gobyexample.com/file-paths
After extracting the extension using `filepath.Ext`, use `strings.TrimSuffix` to get the filename without its extension.
```go
fmt.Println(strings.TrimSuffix(filename, ext))
```
--------------------------------
### Generate Help Text
Source: https://gobyexample.com/command-line-flags
Use the '-h' or '--help' flags to display automatically generated usage information.
```bash
$ ./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
```
--------------------------------
### HTTP Hello Handler
Source: https://gobyexample.com/context
Handles incoming HTTP requests, demonstrating context-based cancellation.
```go
func hello(w http.ResponseWriter, req *http.Request) {
```
```go
ctx := req.Context()
fmt.Println("server: hello handler started")
defer fmt.Println("server: hello handler ended")
```
```go
select {
case <-time.After(10 * time.Second):
fmt.Fprintf(w, "hello\n")
case <-ctx.Done():
err := ctx.Err()
fmt.Println("server:", err)
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
```
--------------------------------
### Main Function Execution
Source: https://gobyexample.com/pointers
The entry point of the program. Initializes a variable, demonstrates pass-by-value and pass-by-pointer modifications, and prints the results.
```go
func main() {
i := 1
fmt.Println("initial:", i)
```
```go
zeroval(i)
fmt.Println("zeroval:", i)
```
```go
zeroptr(&i)
fmt.Println("zeroptr:", i)
```
```go
fmt.Println("pointer:", &i)
}
```
--------------------------------
### Benchmark Function
Source: https://gobyexample.com/testing-and-benchmarking
A benchmark function for `IntMin`. Benchmark functions must start with `Benchmark`. Code that should not be measured goes before the `b.Loop()`.
```go
func BenchmarkIntMin(b *testing.B) {
for b.Loop() {
IntMin(1, 2)
}
}
```
--------------------------------
### Slice from Start in Go
Source: https://gobyexample.com/slices
Omitting the `low` index in the slice operator `[low:]` slices from the specified index to the end of the slice.
```go
l = s[2:]
fmt.Println("sl3:", l)
```
--------------------------------
### Import Necessary Packages
Source: https://gobyexample.com/strings-and-runes
Imports the 'fmt' package for formatted I/O and 'unicode/utf8' for UTF-8 string manipulation.
```go
import (
"fmt"
"unicode/utf8"
)
```
--------------------------------
### Run Go Program with Pre-set Environment Variable
Source: https://gobyexample.com/environment-variables
Demonstrates how a Go program can pick up environment variables set before execution. The `BAR` variable is set to `2` for this execution.
```bash
$ BAR=2 go run environment-variables.go
```
--------------------------------
### Import necessary packages for process spawning
Source: https://gobyexample.com/spawning-processes
Import the required packages for executing external commands and handling errors.
```go
package main
import (
"errors"
"fmt"
"io"
"os/exec"
)
```
--------------------------------
### Initialize Array with Specific Indices
Source: https://gobyexample.com/arrays
Illustrates initializing an array where elements can be assigned to specific indices, with intermediate elements being zeroed if not explicitly set.
```go
b = [...]int{100, 3: 400, 500}
fmt.Println("idx:", b)
```
--------------------------------
### Create and Use a String Channel in Go
Source: https://gobyexample.com/channels
Demonstrates creating a string channel, sending a message from a goroutine, and receiving it. Default channel operations block until both sender and receiver are ready.
```go
package main
```
```go
import "fmt"
```
```go
func main() {
```
```go
messages := make(chan string)
```
```go
go func() { messages <- "ping" }()
```
```go
msg := <-messages
```
```go
fmt.Println(msg)
```
```go
}
```
--------------------------------
### Worker Goroutine Function
Source: https://gobyexample.com/waitgroups
A function simulating a task that runs in a goroutine. It prints start and end messages and sleeps for one second.
```go
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
```
--------------------------------
### Start Worker Goroutines in Go
Source: https://gobyexample.com/worker-pools
Launches multiple worker goroutines concurrently. These workers will wait for jobs to be available on the 'jobs' channel.
```go
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
```
--------------------------------
### Go Main Function
Source: https://gobyexample.com/functions
The 'main' function is the entry point for an executable Go program. It's where program execution begins.
```go
func main() {
res := plus(1, 2)
fmt.Println("1+2 =", res)
res = plusPlus(1, 2, 3)
fmt.Println("1+2+3 =", res)
}
```
--------------------------------
### Main Function in Go
Source: https://gobyexample.com/hello-world
The entry point of a Go program, containing the logic to print 'hello world' using the fmt package.
```go
func main() {
fmt.Println("hello world")
}
```
--------------------------------
### Increment atomic counter in goroutines
Source: https://gobyexample.com/atomic-counters
Starts 50 goroutines, each incrementing the atomic counter 1000 times using `ops.Add(1)`.
```go
for range 50 {
wg.Go(func() {
for range 1000 {
ops.Add(1)
}
})
}
```
--------------------------------
### Create Temporary File in Go
Source: https://gobyexample.com/temporary-files-and-directories
Use os.CreateTemp to create and open a temporary file. Provide an empty string for the directory to use the OS default. The second argument is a filename prefix.
```go
package main
import (
"fmt"
"os"
"path/filepath"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
f, err := os.CreateTemp("", "sample")
check(err)
fmt.Println("Temp file name:", f.Name())
defer os.Remove(f.Name())
_, err = f.Write([]byte{1, 2, 3, 4})
check(err)
```
--------------------------------
### Import necessary packages
Source: https://gobyexample.com/signals
Imports packages for context management, I/O, signal handling, and system calls.
```go
import (
"context"
"fmt"
"os/signal"
"syscall"
)
```
--------------------------------
### Execute a command using bash -c
Source: https://gobyexample.com/spawning-processes
Spawn a command by passing a string to `bash -c`. This allows executing complex commands with arguments as a single string.
```go
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))
}
```
--------------------------------
### Standard Base64 Encoding Output
Source: https://gobyexample.com/base64-encoding
Example output of standard base64 encoding and decoding. Note the specific characters used in the encoded string.
```text
$ go run base64-encoding.go
YWJjMTIzIT8kKiYoKSctPUB~
abc123!?$*&()'-=@~
```
--------------------------------
### Get Current Time in Go
Source: https://gobyexample.com/time
Use `time.Now()` to retrieve the current local time. The output includes the date, time, and timezone offset.
```go
package main
import (
"fmt"
"time"
)
func main() {
p := fmt.Println
now := time.Now()
p(now)
}
```
--------------------------------
### Create Input File for Line Filter
Source: https://gobyexample.com/line-filters
Shell commands to create a sample input file with lowercase lines for testing the Go line filter. This prepares the data to be processed.
```shell
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
```
--------------------------------
### Main Function with State Transitions
Source: https://gobyexample.com/enums
Demonstrates using the enum type and the transition function in the main execution flow.
```go
func main() {
ns := transition(StateIdle)
fmt.Println(ns)
ns2 := transition(ns)
fmt.Println(ns2)
}
```
--------------------------------
### Go Find String Submatch Index with Regexp
Source: https://gobyexample.com/regular-expressions
Finds the indexes of the first match and its submatches within a string. Returns start and end positions for both.
```go
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
```
--------------------------------
### Running a Go Program
Source: https://gobyexample.com/hello-world
Shows the command to execute a Go program directly from its source file using 'go run'.
```bash
$ go run hello-world.go
hello world
```
--------------------------------
### Go Switch with Multiple Cases and Default
Source: https://gobyexample.com/switch
Demonstrates using commas to combine multiple expressions in a single case and utilizing a default case. This is helpful for grouping similar conditions or providing a fallback.
```go
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
```
--------------------------------
### Parse RFC3339 String to Time
Source: https://gobyexample.com/time-formatting-parsing
Parses a time string formatted according to RFC3339 into a time.Time object. Error handling for parsing is omitted for brevity in this example.
```go
t1, _ := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00")
p(t1)
```
--------------------------------
### Handle command execution and exit errors
Source: https://gobyexample.com/spawning-processes
Demonstrates how to differentiate between execution errors (e.g., command not found) and exit errors (non-zero return code) using `errors.AsType`.
```go
_, err = exec.Command("date", "-x").Output()
if err != nil {
if e, ok := errors.AsType[*exec.Error](err); ok {
fmt.Println("failed executing:", e)
} else if e, ok := errors.AsType[*exec.ExitError](err); ok {
exitCode := e.ExitCode()
fmt.Println("command exit rc =", exitCode)
} else {
panic(err)
}
}
```
--------------------------------
### Main Function with WaitGroup
Source: https://gobyexample.com/waitgroups
Initializes a WaitGroup and launches multiple worker goroutines. It then waits for all goroutines to complete.
```go
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Go(func() {
worker(i)
})
}
wg.Wait()
}
```
--------------------------------
### Iterating over slice with index and value
Source: https://gobyexample.com/range-over-built-in-types
When iterating over slices or arrays with 'range', both the index and the value are available. This example demonstrates accessing the index to perform a conditional check.
```go
package main
import "fmt"
func main() {
nums := []int{2, 3, 4}
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
}
```
--------------------------------
### Import necessary packages
Source: https://gobyexample.com/channel-synchronization
Imports the 'fmt' package for formatted I/O and the 'time' package for time-related functions like Sleep.
```go
import (
"fmt"
"time"
)
```