### Install Executable with Go Get Source: https://go.dev/wiki/PackagePublishing Use 'go get' with the full import path to install an executable. This command will also automatically download and install any dependencies, such as the 'epub' package in this example. ```bash go get codesite.tld/authorName/Go-PublishingExample/publish ``` -------------------------------- ### Install Gomote Source: https://go.dev/wiki/Gomote Use the go install command to download and install the latest version of the gomote tool. ```bash $ go install golang.org/x/build/cmd/gomote@latest # Go 1.16 and later ``` -------------------------------- ### Install gomobile tools Source: https://go.dev/wiki/Mobile Install the latest gomobile command-line tools and initialize the environment. ```bash $ go install golang.org/x/mobile/cmd/gomobile@latest $ gomobile init ``` -------------------------------- ### Download binding examples Source: https://go.dev/wiki/Mobile Fetch the example packages used for generating language bindings. ```bash $ go get -d golang.org/x/mobile/example/bind/... ``` -------------------------------- ### Local Multi-Module Setup Source: https://go.dev/wiki/Modules This go.mod example demonstrates using a 'replace' directive with a relative path to link a local module ('hello') to another local module ('goodbye') without relying on VCS. ```go module example.com/me/hello require ( example.com/me/goodbye v0.0.0 ) replace example.com/me/goodbye => ../goodbye ``` -------------------------------- ### Create Instance with Setup Flag Source: https://go.dev/wiki/Gomote Use the -setup flag with the 'create' command to push GOROOT and run make.bash on the instance. This automates the initial setup process. ```bash $ GOROOT=/path/to/my/goroot gomote create -setup gotip-linux-amd64 # Creating user-gotip-linux-amd64-0... # Pushing /path/to/my/goroot to user-gotip-linux-amd64-0 # Running make.bash on user-gotip-linux-amd64-0... ``` -------------------------------- ### Install Library Package with Go Get Source: https://go.dev/wiki/PackagePublishing Use 'go get' with the import path of a specific package to install only that library. Dependencies will be installed if not already present. ```bash go get codesite.tld/authorName/Go-PublishingExample/epub ``` -------------------------------- ### Download mobile example application Source: https://go.dev/wiki/Mobile Fetch the source code for the basic mobile example application. ```bash $ go get -d golang.org/x/mobile/example/basic ``` -------------------------------- ### Create a Hello World program Source: https://go.dev/wiki/ChromeOS A simple Go program to verify the installation. ```go package main import "fmt" func main() { fmt.Println("Hello, Chrome OS!") } ``` -------------------------------- ### Install Go via snap Source: https://go.dev/wiki/Ubuntu Install Go using the snap package manager, which may require a system restart to recognize the command. ```bash sudo snap install --classic go ``` -------------------------------- ### Install a specific tool version with `go install` Source: https://go.dev/wiki/Modules Use `go install tool@version` (since Go 1.16) to install a specific version of a tool. This can eliminate the need for a `tools.go` file. ```bash go install tool@version ``` -------------------------------- ### Install latest Go on Plan 9 Source: https://go.dev/wiki/Plan9 Build and install the latest version of Go after bootstrapping. ```shell cd /tmp git clone https://go.googlesource.com/go cd go/src all.rc bind -a /tmp/go/bin /bin ``` -------------------------------- ### Install Go via PPA Source: https://go.dev/wiki/Ubuntu Use the longsleep/golang-backports PPA to install the latest Go version on supported Ubuntu releases. ```bash sudo add-apt-repository ppa:longsleep/golang-backports sudo apt update sudo apt install golang-go ``` -------------------------------- ### Build and install Android APK Source: https://go.dev/wiki/Mobile Build an Android APK from a Go package and optionally install it to a connected device. ```bash $ gomobile build -target=android -androidapi 19 golang.org/x/mobile/example/basic ``` ```bash $ gomobile install golang.org/x/mobile/example/basic ``` -------------------------------- ### Generic Holder Implementation Example Source: https://go.dev/wiki/Go2GenericsFeedback A conceptual example demonstrating how generic types and methods might be structured using a placeholder syntax. ```go type Key _ type Value _ type IntStringHolder Holder type Holder struct { K Key V Value } func (h *Holder) Set(k Key, v Value) { h.K = k h.V = v } func main() { v:= IntStringHolder{} v.Set(7,"Lucky") } ``` -------------------------------- ### Install and Use Bisect Tool for Debugging Source: https://go.dev/wiki/Go123Timer Install the `bisect` tool and use it with the `-godebug` flag to automatically bisect timer-related failures. ```bash go install golang.org/x/tools/cmd/bisect@latest bisect -godebug asynctimerchan=1 mytest ``` -------------------------------- ### Start a database transaction Source: https://go.dev/wiki/SQLInterface Use `BeginTx` to start a transaction. Operations within the transaction can use `ExecContext`, `QueryContext`, `QueryRowContext`, and `PrepareContext`. Remember to `Commit` or `Rollback` the transaction. ```go tx, err := db.BeginTx(ctx, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Run Local Godoc Server Source: https://go.dev/wiki/PackagePublishing Start a local godoc server to preview package documentation. Browse to http://localhost:6060/pkg/ to view your package documentation. ```bash godoc -http=:6060 & ``` -------------------------------- ### Visualize repository structure Source: https://go.dev/wiki/Modules Examples of repository layouts for internal package imports. ```text my-repo |-- foo | `-- go.mod |-- go.mod `-- internal ``` ```text my-repo |-- foo | `-- go.mod `-- internal `-- go.mod ``` -------------------------------- ### Prepare environment for legacy Go cross-compilation Source: https://go.dev/wiki/WindowsCrossCompiling Install necessary build tools and set environment variables for older Go versions. ```bash sudo apt-get install gcc export go env GOROOT ``` -------------------------------- ### Define a go.mod file Source: https://go.dev/wiki/Modules Example of a go.mod file declaring a module path and its dependencies. ```text module github.com/my/thing require ( github.com/some/dependency v1.2.3 github.com/another/dependency/v4 v4.0.0 ) ``` -------------------------------- ### Go Build Constraints Example Source: https://go.dev/wiki/Comments Illustrates the use of //go:build directives for conditional compilation based on operating system or architecture. ```go //go:build ignore ``` ```go //go:build linux ``` ```go //go:build cgo ``` ```go //go:build purego ``` ```go //go:build amd64 || arm64 ``` ```go //go:build go1.23 ``` -------------------------------- ### Install MinGW/MSYS Configuration Source: https://go.dev/wiki/WindowsBuild This configuration block shows the expected settings when installing MinGW and MSYS. Ensure these components are selected for a successful build. ```text Installing: mingw-get pkginfo C Compiler MSYS Basic System MinGW Developer Toolkit Downloading latest repository catalogues Destination location: C:\MinGW ``` -------------------------------- ### Verify Go Version Source: https://go.dev/wiki/GoArm Check the installed Go version. ```bash abishek@Titan:~$ go version go version go1.12.5 linux/arm64 ``` -------------------------------- ### Spawn Goroutines Source: https://go.dev/wiki/GoForCPPProgrammers Demonstrates starting concurrent execution using the go statement with a function. ```go func server(i int) { for { fmt.Print(i) time.Sleep(10 * time.Second) } } go server(1) go server(2) ``` -------------------------------- ### Partitioning a Hashmap to Reduce Contention Source: https://go.dev/wiki/Performance Example of partitioning a hashmap across multiple `sync.RWMutex` protected partitions to reduce contention on lookups. ```go import "sync" type Partition struct { sync.RWMutex m map[string]string } const partCount = 64 var m [partCount]Partition func Find(k string) string { idx := hash(k) % partCount part := &m[idx] part.RLock() v := part.m[k] part.RUnlock() return v } ``` -------------------------------- ### Go Generate Directive Example Source: https://go.dev/wiki/Comments Shows how to use the //go:generate directive to invoke external tools during the build process. ```go //go:generate stringer -type=Enum ``` -------------------------------- ### Bootstrap Go 1.4 on Plan 9 Source: https://go.dev/wiki/Plan9 Install Go 1.4.3 as a bootstrap compiler on Plan 9, including the necessary syscall-exec patch for SMP machines. ```shell cd /tmp git clone -b go1.4.3 https://go.googlesource.com/go go1.4 cd go1.4/src hget http://9legacy.org/go/patch/syscall-exec.diff | ape/patch -p2 make.rc ``` -------------------------------- ### Diagnose Module Path Errors Source: https://go.dev/wiki/Resolving-Problems-From-Modified-Module-Path Example of a failed go get command due to an unexpected module path. ```bash $ cd my-go-project $ go get -u ./... [...] go: github.com/golang/lint@v0.0.0-20190313153728-d0100b6bd8b3: parsing go.mod: unexpected module path "golang.org/x/lint" [...] Exit code 1 ``` -------------------------------- ### Scheduler Trace Output Example Source: https://go.dev/wiki/Performance Example output from a scheduler trace, showing time since program start, GOMAXPROCS, idle processors, threads, idle threads, run queue length, and per-processor queue lengths. ```text SCHED 1004ms: gomaxprocs=4 idleprocs=0 threads=11 idlethreads=4 runqueue=8 [0 1 0 3] SCHED 2005ms: gomaxprocs=4 idleprocs=0 threads=11 idlethreads=5 runqueue=6 [1 5 4 0] SCHED 3008ms: gomaxprocs=4 idleprocs=0 threads=11 idlethreads=4 runqueue=10 [2 2 2 1] ``` -------------------------------- ### Define Go version-specific tags Source: https://go.dev/wiki/PackagePublishing Examples of tag naming conventions for Go releases and weekly builds used by the go get tool. ```text go.r60 -- A "go.r##" tag will be checked out if the user has that Go release installed go.weekly.2011-07-19 -- A "go.weekly.YYYY-MM-DD" tag will be checked out if the user has that weekly installed ``` -------------------------------- ### Call Hosted AI Service with Go Source: https://go.dev/wiki/AI Example demonstrating how to call a hosted AI service from Go. Requires setting up a client, assembling a message with a prompt, sending it, and receiving a reply. ```Go package main import ( "context" "fmt" "log" "github.com/googleapis/go-genai/genai" "google.golang.org/api/option" ) func main() { ctx := context.Background() // TODO(developer): Set your API key here // For more information, see https://ai.google.dev/tutorials/setup apiKey := "YOUR_API_KEY" client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey)) if err != nil { log.Fatal(err) } defer client.Close() model := client.GenerativeModel("gemini-1.0-pro") resp, err := model.GenerateContent(ctx, genai.Text("Write a short story about a robot learning to love.")) if err != nil { log.Fatal(err) } fmt.Println(resp.Candidates[0].Content.Parts[0]) } ``` -------------------------------- ### Reproduce Rare Failure with Groups Source: https://go.dev/wiki/Gomote Combine group management, instance creation with setup, and pattern-based command execution to efficiently reproduce rare failures. This example hammers a test across multiple instances. ```bash $ export GOMOTE_GROUP=debug $ GOROOT=/path/to/goroot gomote create -setup -count=10 gotip-linux-amd64 $ gomote run -until='unexpected return pc' -collect go/bin/go run -run="TestFlaky" -count=100 runtime ``` -------------------------------- ### Create a Simple HTTP Server Source: https://go.dev/wiki/CoreDumpDebugging A basic Go web server implementation for testing core dump generation. ```go $ cat main.go package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello world\n") }) log.Fatal(http.ListenAndServe("localhost:7777", nil)) } ``` -------------------------------- ### Control Flow Syntax Examples Source: https://go.dev/wiki/GoForCPPProgrammers Examples of valid and invalid syntax for if and for statements in Go. ```go if (a < b) { f() } // Valid (condition is a parenthesized expression) if (a < b) f() // INVALID for i = 0; i < 10; i++ {} // Valid for (i = 0; i < 10; i++) {} // INVALID ``` -------------------------------- ### Serve WebAssembly Files with HTTP Source: https://go.dev/wiki/WebAssembly Serve the WebAssembly module, JavaScript support file, and HTML page using a basic HTTP server. This example uses `goexec` for convenience. ```bash # install goexec: go install github.com/shurcooL/goexec@latest goexec 'http.ListenAndServe(`:8080`, http.FileServer(http.Dir(`.`)))' ``` -------------------------------- ### Bootstrap from binary package Source: https://go.dev/wiki/Plan9 Download and extract the pre-built binary package for bootstrapping on plan9/386. ```shell cd /tmp hget -o gobootstrap-plan9-386.tar.gz https://storage.googleapis.com/go-builder-data/gobootstrap-plan9-386.tar.gz mkdir gobootstrap-plan9-386 cd gobootstrap-plan9-386 tar xzf ../gobootstrap-plan9-386.tar.gz ``` -------------------------------- ### Build Go from Source on Windows Source: https://go.dev/wiki/WindowsBuild These commands clone the Go repository and build it using the `all.bat` script. Ensure MinGW/MSYS is set up correctly before running. ```bash git clone https://go.googlesource.com/go cd go\src all.bat ``` -------------------------------- ### Go Package Build Example Source: https://go.dev/wiki/PackagePublishing This Go code defines a main package that uses an external 'epub' package. Ensure all files in the same directory share the same package name. ```go package main import ( "flag" ) import "codesite.tld/authorName/Go-PublishingExample/epub" var dir = flag.String("dir", ".", "Directory to publish") func main() { flag.Parse() epub.Publish(*dir) } ``` -------------------------------- ### Verbose Dependency Fetching Source: https://go.dev/wiki/Modules When `go get` or `go build` fails, use `go get -v foo` for more verbose output, which can reveal detailed error messages. For even more insight, including VCS commands, use `go get -v -x foo`. ```bash go get -v foo ``` ```bash go get -v -x foo ``` -------------------------------- ### List All Dependencies Source: https://go.dev/wiki/Modules Use `go list -m all` to view the final versions of all direct and indirect dependencies that will be used in a build. ```bash $ go list -m all ``` -------------------------------- ### Open a database connection Source: https://go.dev/wiki/SQLInterface Use `sql.Open` to create a database handle. It does not establish a connection immediately; this is deferred until a query is made. Use `PingContext` to verify connectivity. ```go db, err := sql.Open(driver, dataSourceName) ``` ```go if err := db.PingContext(ctx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Build the Go Binary Source: https://go.dev/wiki/CoreDumpDebugging Compile the Go source code into an executable binary. ```bash $ go build . ``` -------------------------------- ### Windows: Subrepo Upload and Test Source: https://go.dev/wiki/Gomote Upload a compressed subrepository to a Windows gomote instance using 'gomote puttar' and then run tests. This example uses GOPATH and specific test flags. ```bash $ tar --exclude .git -C ~/go/src/ -zc golang.org/x/tools | gomote puttar -dir=gopath/src $MOTE - $ gomote run -e 'GOPATH=%WORKDIR%\gopath' $MOTE go/bin/go test -run=TestFixImportsVendorPackage golang.org/x/tools/imports ``` -------------------------------- ### Shortage of Work Scheduler Example Source: https://go.dev/wiki/Performance An example of a scheduler trace output demonstrating a shortage of work to keep all processors busy, characterized by high idleprocs and low runqueue lengths. ```text gomaxprocs=8 idleprocs=6 threads=40 idlethreads=30 runqueue=0 [0 2 0 0 0 1 0 0] ``` -------------------------------- ### Upgrade Dependencies Using Go Tip Source: https://go.dev/wiki/Modules Use this command sequence to download the Go tip version and upgrade all dependencies. This can help resolve module name conflicts by leveraging improved upgrade logic. ```bash go get golang.org/dl/gotip && gotip download gotip get -u all gotip mod tidy ``` -------------------------------- ### Memory Allocator Trace Output Example Source: https://go.dev/wiki/Performance Example output from a memory allocator trace, showing allocation and free operations with details like address, size, type, and goroutine stack traces. ```text tracealloc(0xc208062500, 0x100, array of parse.Node) goroutine 16 [running]: runtime.mallocgc(0x100, 0x3eb7c1, 0x0) runtime/malloc.goc:190 +0x145 fp=0xc2080b39f8 runtime.growslice(0x31f840, 0xc208060700, 0x8, 0x8, 0x1, 0x0, 0x0, 0x0) runtime/slice.goc:76 +0xbb fp=0xc2080b3a90 text/template/parse.(*Tree).parse(0xc2080820e0, 0xc208023620, 0x0, 0x0) text/template/parse/parse.go:289 +0x549 fp=0xc2080b3c50 ... tracefree(0xc208002d80, 0x120) goroutine 16 [running]: runtime.MSpan_Sweep(0x73b080) runtime/mgc0.c:1880 +0x514 fp=0xc20804b8f0 runtime.MCentral_CacheSpan(0x69c858) runtime/mcentral.c:48 +0x2b5 fp=0xc20804b920 runtime.MCache_Refill(0x737000, 0xc200000012) runtime/mcache.c:78 +0x119 fp=0xc20804b950 ... ``` -------------------------------- ### Ideal Scheduler State Example Source: https://go.dev/wiki/Performance An example of an ideal scheduler trace output, indicating that all processors are busy executing Go code, the number of threads is reasonable, and work is evenly distributed across queues. ```text gomaxprocs=8 idleprocs=0 threads=40 idlethreads=5 runqueue=10 [20 20 20 20 20 20 20 20] ``` -------------------------------- ### Visualize CPU Profile with --web Source: https://go.dev/wiki/Performance An example of a CPU profile visualized using the `--web` option of `go tool pprof`. This provides a graphical representation of function call stacks and their CPU usage. ```text . . 93: func (bp *buffer) WriteRune(r rune) error { . . 94: if r < utf8.RuneSelf { 5 5 95: *bp = append(*bp, byte(r)) . . 96: return nil . . 97: } . . 98: . . 99: b := *bp . . 100: n := len(b) . . 101: for n+utf8.UTFMax > cap(b) { . . 102: b = append(b, 0) . . 103: } . . 104: w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r) . . 105: *bp = b[:n+w] . . 106: return nil . . 107: } ``` -------------------------------- ### Update Dependencies Source: https://go.dev/wiki/Modules Update all direct and indirect dependencies to their latest minor or patch versions using `go get -u ./...` or `go get -u=patch ./...` from the module root directory. ```bash $ go get -u ./... $ go get -u=patch ./... ``` -------------------------------- ### Build Windows executable with legacy Go Source: https://go.dev/wiki/WindowsCrossCompiling Compile the source code into a Windows executable after the environment is prepared. ```bash $ cat hello.go package main import "fmt" func main() { fmt.Printf("Hello\n") } $ GOOS=windows GOARCH=386 go build -o hello.exe hello.go ``` -------------------------------- ### Build or Test All Packages Source: https://go.dev/wiki/Modules Build or test all packages within the module by running `go build ./...` or `go test ./...` from the module root directory. ```bash $ go build ./... $ go test ./... ``` -------------------------------- ### Define a nested module structure Source: https://go.dev/wiki/Modules Example of a repository structure where a module is nested within a subdirectory. ```text my-repo `-- foo `-- rop `-- go.mod ``` -------------------------------- ### Manage Prompts with Go Text Template Source: https://go.dev/wiki/AI Example showing how to manage prompts with variables using Go's text/template package. This is useful for dynamically generating prompts based on user input. ```Go package main import ( "log" "os" "text/template" ) func main() { const tpl = `Hello, {{.Name}}! Welcome to {{.Location}}. ` t = template.Must(template.New("tpl").Parse(tpl)) data := struct { Name string Location string }{ Name: "Gopher", Location: "Go Wiki", } err := t.Execute(os.Stdout, data) if err != nil { log.Println("Error executing template:", err) } } ``` -------------------------------- ### GC Trace Output Example Source: https://go.dev/wiki/Performance Sample output generated by the Go runtime when GODEBUG=gctrace=1 is enabled. ```text gc9(2): 12+1+744+8 us, 2 -> 10 MB, 108615 (593983-485368) objects, 4825/3620/0 sweeps, 0(0) handoff, 6(91) steal, 16/1/0 yields gc10(2): 12+6769+767+3 us, 1 -> 1 MB, 4222 (593983-589761) objects, 4825/0/1898 sweeps, 0(0) handoff, 6(93) steal, 16/10/2 yields gc11(2): 799+3+2050+3 us, 1 -> 69 MB, 831819 (1484009-652190) objects, 4825/691/0 sweeps, 0(0) handoff, 5(105) steal, 16/1/0 yields ``` -------------------------------- ### Format Package Comments Source: https://go.dev/wiki/CodeReviewComments Examples of standard package comment formats that appear correctly in godoc. ```go // Package math provides basic constants and mathematical functions. package math ``` ```go /* Package template implements data-driven templates for generating textual output such as HTML. .... */ package template ``` -------------------------------- ### List Available Builder Types Source: https://go.dev/wiki/Gomote Display all available instance types that can be created. ```bash $ gomote create -list (list tons of builder types) ``` -------------------------------- ### Reflect MapIndex usage attempt Source: https://go.dev/wiki/HowToAsk An example of incorrect usage of the reflect package that results in a panic. ```go m := make(map[string]int) v := reflect.ValueOf(m) key := reflect.ValueOf("hello") val := reflect.ValueOf(123) v.MapIndex(k).Set(val) print(m) ``` -------------------------------- ### Initial slices.Backward usage Source: https://go.dev/wiki/RangefuncExperiment The starting point for the compiler optimization process using a range-over-function pattern. ```go slices.Backward(s)(func(i int, x string) bool { fmt.Println(i, x) return true }) ``` -------------------------------- ### Build and Run a Go Application Source: https://go.dev/wiki/Modules After writing your code and ensuring dependencies are managed with `go mod tidy`, you can build and run your application using `go build` and executing the compiled binary. ```bash $ go mod tidy go: finding module for package rsc.io/quote go: found rsc.io/quote in rsc.io/quote v1.5.2 $ go build -o hello $ ./hello Hello, world. ``` -------------------------------- ### Set GOROOT_BOOTSTRAP environment variable Source: https://go.dev/wiki/Plan9 Set the GOROOT_BOOTSTRAP variable to point to the bootstrap Go installation directory. ```shell GOROOT_BOOTSTRAP=/tmp/go1.4 ``` -------------------------------- ### Define a GitHub-hosted multi-module repository structure Source: https://go.dev/wiki/Modules Example of a repository structure hosted on GitHub with multiple modules. ```text github.com/my-repo |-- bar |-- foo | |-- rop | `-- yut |-- go.mod `-- mig `-- vub ``` -------------------------------- ### Allocate buffered channel with make Source: https://go.dev/wiki/GoForCPPProgrammers Demonstrates allocating a buffered channel using the `make` function with a specified capacity. ```go make(chan int, 10) ``` -------------------------------- ### Define a multi-module repository structure Source: https://go.dev/wiki/Modules Example of a repository containing multiple modules at different directory levels. ```text my-repo |-- bar |-- foo | |-- rop | `-- yut |-- go.mod `-- mig |-- go.mod `-- vub ```