### Build and Install Local Package Source: https://go.dev/doc/articles/go_command Demonstrates navigating to a package directory, running verbose tests, and installing the package using 'go install'. ```bash cd github.com/google/codesearch/regexp go list go test -v go install ``` -------------------------------- ### Automated Contributor Initialization Tool Source: https://go.dev/doc/contribute.html Installs and runs an automated tool that guides users through the initial setup steps for contributing to Go projects. This includes configuring Git and potentially other necessary environment settings. ```bash go install golang.org/x/tools/cmd/go-contrib-init@latest cd /code/to/edit go-contrib-init ``` -------------------------------- ### Initializing and Committing a Git Repository for a Go Module Source: https://go.dev/doc/modules/managing-source This example demonstrates the basic Git commands to initialize a new repository, add all project files, commit them with a message, and push to a remote. This is a common workflow for starting a new Go module. ```bash $ git init $ git add --all $ git commit -m "mycode: initial commit" $ git push ``` -------------------------------- ### Install Go Tour Source: https://go.dev/doc Installs the Go Tour binary locally for an interactive introduction to Go. ```bash $ go install golang.org/x/website/tour@latest ``` -------------------------------- ### Install and Download Additional Go Versions Source: https://go.dev/doc/manage-install Uses the go install command to fetch a specific Go version and the download command to initialize it. Requires git to be installed on the system. ```bash go install golang.org/dl/go1.10.7@latest go1.10.7 download ``` -------------------------------- ### Fetch and Install Go Packages Source: https://go.dev/doc/articles/go_command Uses the 'go get' command to download and install external libraries from version control repositories into the GOPATH workspace. ```bash go get github.com/google/codesearch/index go get github.com/petar/GoLLRB/llrb ``` -------------------------------- ### Installing and Running a Go Program Source: https://go.dev/doc/code Installs the 'hello' program, making it executable from the command line. Subsequently, it runs the program to display the output generated by the imported 'morestrings' package. ```bash go install example/user/hello hello ``` -------------------------------- ### Go Package Comment Example Source: https://go.dev/doc/comment An example of a Go package comment that introduces the package and provides important usage information. Package comments should start with 'Package ' and use complete sentences. Square brackets create documentation links. ```go // Package path implements utility routines for manipulating slash-separated // paths. // // The path package should only be used for paths separated by forward // slashes, such as the paths in URLs. This package does not deal with // Windows paths with drive letters or backslashes; to manipulate // operating system paths, use the [path/filepath] package. package path ``` -------------------------------- ### Verify Go Installation (Linux/Mac) Source: https://go.dev/doc/install Checks if Go has been installed correctly by displaying the installed version. Open a command prompt to run this. ```bash $ go version ``` -------------------------------- ### Go Module Toolchain Update Example Source: https://go.dev/doc/toolchain This example demonstrates how commands like `go get` update the `toolchain` line in `go.mod` or `go.work` files after switching to a new Go version. This ensures repeatability by selecting the same toolchain on subsequent runs. ```go toolchain go1.27.9 ``` -------------------------------- ### Install Programs from a cmd Directory Source: https://go.dev/doc/modules/layout Commands to install Go binaries when they are organized within a standard cmd subdirectory structure. This is the recommended practice for mixed-content repositories. ```bash $ go install github.com/someuser/modname/cmd/prog1@latest $ go install github.com/someuser/modname/cmd/prog2@latest ``` -------------------------------- ### Verify Go Installation Source: https://go.dev/doc/install/source A simple Go program to verify that the compiler and toolchain are correctly installed and functional. ```go package main import "fmt" func main() { fmt.Printf("hello, world\n") } ``` -------------------------------- ### Install Go Programs from a Repository Source: https://go.dev/doc/modules/layout Commands to install specific Go programs hosted in a repository using the go install tool. These commands target specific subdirectories containing main packages. ```bash $ go install github.com/someuser/modname/prog1@latest $ go install github.com/someuser/modname/prog2@latest ``` -------------------------------- ### Install External Package `nntp-go` using `goinstall` Source: https://go.dev/doc/devel/weekly Demonstrates how to install the `nntp` package, which has been removed from the standard library and is now hosted as `nntp-go` on Google Code. The `goinstall` command is used to fetch and install this external package, after which it can be imported into Go projects. ```bash goinstall nntp-go.googlecode.com/hg/nntp ``` ```go import "nntp-go.googlecode.com/hg/nntp" ``` -------------------------------- ### Install Go Command Source: https://go.dev/doc/modules/layout Installs a Go command-line program. This command fetches the latest version of the specified module and installs its executable, making it available in the system's PATH. This is a common way to distribute and use Go tools. ```bash $ go install github.com/someuser/modname@latest ``` -------------------------------- ### Go Function Signature Examples Source: https://go.dev/doc/go_spec.html Provides practical examples of Go function signatures, demonstrating different ways to define parameters and return values, including named and unnamed parameters, and variadic arguments. ```go func() func(x int) int func(a, _ int, z float32) bool func(a, b int, z float32) (bool) func(prefix string, values ...int) func(a, b int, z float64, opt ...interface{}) (success bool) func(int, int, float64) (float64, *[]int) func(n int) func(p *T) ``` -------------------------------- ### Go Module and Program Example for Coverage Source: https://go.dev/doc/build-cover A sample Go project structure including a go.mod file, a main package, and a local module package ('greetings'). This example demonstrates how packages are selected for coverage profiling during the build process. ```go package main import ( "fmt" "mydomain.com/greetings" "rsc.io/quote" ) func main() { fmt.Printf("I say %q and %q\n", quote.Hello(), greetings.Goodbye()) } ``` ```go package greetings func Goodbye() string { return "see ya" } ``` ```bash module mydomain.com go 1.20 require rsc.io/quote v1.5.2 require ( golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect rsc.io/sampler v1.3.0 // indirect ) ``` -------------------------------- ### Go Function Doc Comment Example (math.Sqrt) Source: https://go.dev/doc/comment Illustrates documenting special cases for a mathematical function. This example details the behavior of math.Sqrt for infinite, zero, negative, and NaN inputs. ```go package math // Sqrt returns the square root of x. // // Special cases are: // // Sqrt(+Inf) = +Inf // Sqrt(±0) = ±0 // Sqrt(x < 0) = NaN // Sqrt(NaN) = NaN func Sqrt(x float64) float64 { ... } ``` -------------------------------- ### Initializing and Committing with Git Source: https://go.dev/doc/code Demonstrates the basic steps for initializing a Git repository, adding Go source files, and making an initial commit. This is an optional step for version control. ```bash git init git add go.mod hello.go git commit -m "initial commit" ``` -------------------------------- ### Go Continue Statement Examples Source: https://go.dev/doc/go_spec.html Demonstrates the 'continue' statement in Go, which starts the next iteration of the innermost enclosing 'for' loop. It shows how to use labels to continue specific loops in nested structures. ```Go RowLoop: for y, row := range rows { for x, data := range row { if data == endOfRow { continue RowLoop } row[x] = data + bias(x, y) } } ``` -------------------------------- ### Initialize Go Module and Project Structure Source: https://go.dev/doc/tutorial/govulncheck Commands to create a new directory and initialize a Go module for the vulnerability tutorial. ```bash mkdir vuln-tutorial cd vuln-tutorial go mod init vuln.tutorial ``` -------------------------------- ### Go Function Doc Comment Example (strings.HasPrefix) Source: https://go.dev/doc/comment Shows a doc comment for a boolean-returning function, using the phrase 'reports whether' as per convention. This function checks if a string starts with a specified prefix. ```go package strings // HasPrefix reports whether the string s begins with prefix. func HasPrefix(s, prefix string) bool ``` -------------------------------- ### Upgrade Go Dependency using go get Source: https://go.dev/doc/tutorial/govulncheck This command upgrades a specific Go package to a designated version. It's useful for patching security vulnerabilities. Ensure you have Go installed and your project is set up correctly. ```bash $ go get golang.org/x/text@v0.3.8 ``` -------------------------------- ### Initialize Go Wiki Project Directory Source: https://go.dev/doc/articles/wiki Commands to create a new directory for the wiki project and navigate into it using the command line. ```bash $ mkdir gowiki $ cd gowiki ``` -------------------------------- ### Go Benchmark Function Example Source: https://go.dev/doc/go1 Demonstrates a benchmark function using the testing.B type in Go. It includes setup for correctness verification and the core benchmarking loop. This pattern is used for performance testing of Go code. ```go func BenchmarkSprintf(b *testing.B) { // Verify correctness before running benchmark. b.StopTimer() got := fmt.Sprintf("%x", 23) const expect = "17" if expect != got { b.Fatalf("expected %q; got %q", expect, got) } b.StartTimer() for i := 0; i < b.N; i++ { fmt.Sprintf("%x", 23) } } ``` -------------------------------- ### Create Project Directory and Module Source: https://go.dev/doc/tutorial/generics Sets up a new directory for Go generics code and initializes a Go module. This is the first step in creating a new Go project. ```bash mkdir generics cd generics go mod init example/generics ``` -------------------------------- ### Go Type and Method Documentation Example (bytes.Buffer) Source: https://go.dev/doc/comment Demonstrates how Go documentation displays a type (Buffer) along with its constructor functions and methods. It shows the structure for documenting types and their associated operations. ```go package bytes // import "bytes" type Buffer struct { // Has unexported fields. } A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use. func NewBuffer(buf []byte) *Buffer func NewBufferString(s string) *Buffer func (b *Buffer) Bytes() []byte func (b *Buffer) Cap() int func (b *Buffer) Grow(n int) func (b *Buffer) Len() int func (b *Buffer) Next(n int) []byte func (b *Buffer) Read(p []byte) (n int, err error) func (b *Buffer) ReadByte() (byte, error) ... ``` -------------------------------- ### Create Simple Web Server with Go net/http Source: https://go.dev/doc/articles/wiki This Go program demonstrates how to create a basic web server using the net/http package. It sets up a handler for the root path and listens on port 8080. The handler formats a response based on the requested URL path. ```go //go:build ignore package main import ( "fmt" "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Go godoc HTML Example Output Improvement Source: https://go.dev/doc/devel/weekly Highlights improvements in the `godoc` tool for rendering example output in HTML. This enhances the readability and presentation of code examples in documentation. ```go // godoc: improved output of examples in html (thanks Volker Dobler). ``` -------------------------------- ### Go Map Initialization using make Source: https://go.dev/doc/go_spec.html Demonstrates how to create new, empty map values using the built-in `make` function. An optional capacity hint can be provided to optimize initial memory allocation. ```Go make(map[string]int) ``` ```Go make(map[string]int, 100) ``` -------------------------------- ### Go Channel Initialization using make Source: https://go.dev/doc/go_spec.html Shows how to create initialized channel values using the `make` function. Channels can be unbuffered (capacity 0) or buffered with a specified capacity. ```Go make(chan int, 100) ``` -------------------------------- ### Create Go 'Hello, World!' Program Source: https://go.dev/doc/tutorial/getting-started This Go code defines a main package and a main function that prints 'Hello, World!' to the console. It utilizes the standard 'fmt' package for output operations. This is a fundamental example for beginners learning Go. ```go package main import "fmt" func main() { fmt.Println("Hello, World!") } ``` -------------------------------- ### Example go.work File Configuration Source: https://go.dev/doc/tutorial/workspaces Shows the structure of a go.work file, which specifies the Go version and the modules included in the workspace using the use directive. ```text go 1.18 use ./hello ``` -------------------------------- ### Create and Navigate to Directory Source: https://go.dev/doc/tutorial/getting-started Commands to create a new directory named 'hello' and then change the current directory into it. This is typically done to set up a new project. ```bash mkdir hello cd hello ``` -------------------------------- ### Install Additional Go Tools Source: https://go.dev/doc/install/source Command to install supplemental Go tools, such as gopls, from the official tools repository. ```bash go install golang.org/x/tools/gopls@latest ``` -------------------------------- ### Go goinstall Flag Handling Source: https://go.dev/doc/devel/weekly Explains that `goinstall` now honors the `-install=false` flag when the `-make=true` flag is also used, providing more control over the installation process. ```go // goinstall: honour -install=false flag when -make=true. ``` -------------------------------- ### Go: Configure Gin Router for POST and GET Requests Source: https://go.dev/doc/tutorial/web-service-gin This Go code initializes a Gin router and defines routes for both GET and POST requests to the '/albums' endpoint. It associates the '/albums' path with the 'getAlbums' handler for GET requests and 'postAlbums' for POST requests. ```go func main() { router := gin.Default() router.GET("/albums", getAlbums) router.POST("/albums", postAlbums) router.Run("localhost:8080") } ``` -------------------------------- ### Initialize MySQL Database Connection in Go Source: https://go.dev/doc/tutorial/database-access This snippet demonstrates how to configure a MySQL connection using the driver's Config struct, open a database handle, and verify the connection with a ping. ```go var db *sql.DB func main() { cfg := mysql.NewConfig() cfg.User = os.Getenv("DBUSER") cfg.Passwd = os.Getenv("DBPASS") cfg.Net = "tcp" cfg.Addr = "127.0.0.1:3306" cfg.DBName = "recordings" var err error db, err = sql.Open("mysql", cfg.FormatDSN()) if err != nil { log.Fatal(err) } pingErr := db.Ping() if pingErr != nil { log.Fatal(pingErr) } fmt.Println("Connected!") } ``` -------------------------------- ### Remove Previous Go Installation (Linux) Source: https://go.dev/doc/install Deletes any existing Go installation before extracting the new version. Run with root or sudo permissions. ```bash $ rm -rf /usr/local/go && tar -C /usr/local -xzf go1.26.4.linux-amd64.tar.gz ``` -------------------------------- ### Build and Install Gold Linker Source: https://go.dev/doc/install/gccgo Commands to clone, configure, and install the GNU gold linker from source, enabling split-stack support for goroutines. ```bash git clone git://sourceware.org/git/binutils-gdb.git mkdir binutils-objdir cd binutils-objdir ../binutils-gdb/configure --enable-gold=default --prefix=/opt/gold make make install ``` -------------------------------- ### Expression Statement Examples Source: https://go.dev/doc/go_spec.html Examples of valid and invalid expression statements in Go, noting that certain built-in functions cannot be used as standalone statements. ```go h(x+y) f.Close() <-ch (<-ch) len("foo") // illegal if len is the built-in function ``` -------------------------------- ### Test Page Persistence in Main Source: https://go.dev/doc/articles/wiki A main function demonstrating how to initialize a Page, save it to disk, reload it, and print the content to verify the persistence logic. ```go func main() { p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")} p1.save() p2, _ := loadPage("TestPage") fmt.Println(string(p2.Body)) } ``` -------------------------------- ### Display Go Help Source: https://go.dev/doc/tutorial/getting-started This command displays a list of available Go commands and their brief descriptions, useful for exploring the Go toolchain. ```bash go help ``` -------------------------------- ### Get a specific branch of a module Source: https://go.dev/doc/modules/managing-dependencies Use `go get` with `@` to fetch a module from a specific branch. This is useful for testing changes on a particular branch. ```bash $ go get example.com/theirmodule@bugfixes ``` -------------------------------- ### Go Floating-Point Literal Syntax Examples Source: https://go.dev/doc/go_spec.html Provides examples of valid decimal and hexadecimal floating-point literals, including scientific notation and the use of underscores for readability. ```go 0. 72.40 2.71828 1.e+0 6.67428e-11 1E6 .25 .12345E+5 1_5. 0.15e+0_2 0x1p-2 0x2.p10 0x1.Fp+0 0X.8p-0 0X_1FFFP-16 ``` -------------------------------- ### Get a specific commit of a module Source: https://go.dev/doc/modules/managing-dependencies Use `go get` with `@` to fetch a module at a specific commit. This adds a `require` directive with a pseudo-version to your `go.mod` file. ```bash $ go get example.com/theirmodule@4cf76c2 ``` -------------------------------- ### Create a Basic Go Program Source: https://go.dev/doc/code A standard Hello World program in Go. It uses the main package and imports the fmt package to print text to the console. ```go package main import "fmt" func main() { fmt.Println("Hello, world.") } ``` -------------------------------- ### Go crypto/tls Certificate Generation Example Update Source: https://go.dev/doc/devel/weekly The example for certificate generation in the crypto/tls package now utilizes rand.Reader for enhanced randomness, improving the security of generated certificates. ```go import ( "crypto/rand" "crypto/tls" ) func generateCert() (*tls.Certificate, error) { // Example usage of rand.Reader (details omitted for brevity) // cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) // if err != nil { // return nil, err // } // return &cert, nil return nil, nil // Placeholder } ``` -------------------------------- ### Running Go Tests with `go test` Source: https://go.dev/doc/code This example shows the command-line usage for running Go tests within a specific package directory. It involves navigating to the package's directory and executing the `go test` command. The output indicates whether the tests passed or failed, along with the time taken. ```Shell cd $HOME/hello/morestrings **go test** ``` -------------------------------- ### Go Undetected Dependency Example Source: https://go.dev/doc/go_spec.html Shows a Go example where a hidden, undetected dependency exists, leading to unspecified initialization order between certain variables and the execution of side effects. ```go var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b var _ = sideEffect() // unrelated to x, a, or b var a = b var b = 42 type I interface { ab() []int } type T struct{} func (T) ab() []int { return []int{a, b} } ``` -------------------------------- ### Go Type Constraint Satisfaction Examples Source: https://go.dev/doc/go_spec.html Provides examples of type arguments satisfying type constraints in Go, including cases that leverage the exception for strictly comparable constraints. ```go type argument type constraint // constraint satisfaction int interface{ ~int } // satisfied: int implements interface{ ~int } string comparable // satisfied: string implements comparable (string is strictly comparable) []byte comparable // not satisfied: slices are not comparable any interface{ comparable; int } // not satisfied: any does not implement interface{ int } any comparable // satisfied: any is comparable and implements the basic interface any struct{f any} comparable // satisfied: struct{f any} is comparable and implements the basic interface any any interface{ comparable; m() } // not satisfied: any does not implement the basic interface interface{ m() } interface{ m() } interface{ comparable; m() } // satisfied: interface{ m() } is comparable and implements the basic interface interface{ m() } ``` -------------------------------- ### Go Initialization with Function Calls and Dependencies Source: https://go.dev/doc/go_spec.html Illustrates a more complex initialization scenario in Go, showing how function calls and inter-variable dependencies affect the initialization order. Note that 'd' is modified within 'f()'. ```go var ( a = c + b // == 9 b = f() // == 4 c = f() // == 5 d = 3 // == 5 after initialization has finished ) func f() int { d++ return d } ``` -------------------------------- ### Go URL Parsing Example Source: https://go.dev/doc/go1 Illustrates the structure of a parsed URL using the url.URL type in Go 1.x. This example shows how mailto URLs are parsed with the Opaque field and RawQuery. ```go URL{ Scheme: "mailto", Opaque: "dev@golang.org", RawQuery: "subject=Hi", } ``` -------------------------------- ### Create Package Documentation in go/doc Source: https://go.dev/doc/go1 Demonstrates the updated method for creating package documentation in the go/doc package using the new New function with a mode parameter. ```go doc.New(pkg, importpath, mode) ```