### Go Package Import Example
Source: https://go.dev/doc/effective_go/index
Demonstrates how to import a package in Go and access its contents using the package name as an accessor. The convention is to use short, lowercase, single-word package names.
```go
import "bytes"
// Accessing a type from the bytes package:
var buf bytes.Buffer
```
--------------------------------
### Go: Basic Formatted Printing Examples
Source: https://go.dev/doc/effective_go/index
Demonstrates equivalent output using different fmt functions like Printf, Fprintf, and Println for basic string and integer formatting. These functions are part of the 'fmt' package.
```Go
fmt.Printf("Hello %d\n", 23)
fmt.Fprint(os.Stdout, "Hello ", 23, "\n")
fmt.Println("Hello", 23)
fmt.Println(fmt.Sprint("Hello ", 23))
```
--------------------------------
### Go Panic Example: Critical Initialization Failure
Source: https://go.dev/doc/effective_go/index
Illustrates using 'panic' in Go during the 'init' function when a critical environment variable, such as '$USER', is not set. This prevents the program from starting in an invalid or incomplete state.
```Go
package main
import (
"fmt"
"os"
)
var user = os.Getenv("USER")
func init() {
if user == "" {
panic("no value for $USER")
}
}
func main() {
fmt.Printf("Hello, %s!\n", user)
}
```
--------------------------------
### Using io.Writer with ByteSlice
Source: https://go.dev/doc/effective_go/index
Example demonstrating how to use the 'io.Writer' interface with a 'ByteSlice'. It shows that only a pointer to 'ByteSlice' satisfies 'io.Writer', and explains the compiler's automatic address insertion for method calls on addressable values.
```go
var b ByteSlice
fmt.Fprintf(&b, "This hour has %d days\n", 7)
```
--------------------------------
### Go Init Function for Program Setup
Source: https://go.dev/doc/effective_go/index
Demonstrates the use of the `init` function in Go for package initialization. Init functions run after variable declarations and imported package initializations. They are used for setting up state, verification, or overriding default values.
```go
func init() {
if user == "" {
log.Fatal("$USER not set")
}
if home == "" {
home = "/home/" + user
}
if gopath == "" {
gopath = home + "/go"
}
// gopath may be overridden by --gopath flag on command line.
flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH")
}
```
--------------------------------
### Go Slicing a Buffer for Reading
Source: https://go.dev/doc/effective_go/index
An example of slicing a buffer to read into the first 32 bytes. This is a common and efficient way to specify a portion of a slice for operations like reading data.
```go
n, err := f.Read(buf[0:32])
```
--------------------------------
### Go Simple If Statement
Source: https://go.dev/doc/effective_go/index
A basic example of an 'if' statement in Go. The body of the 'if' statement must be enclosed in braces.
```go
if x > 0 {
return y
}
```
--------------------------------
### Register HTTP Handler in Go
Source: https://go.dev/doc/effective_go/index
Example of how to attach a custom HTTP handler (an instance of `Counter`) to a specific URL path (`/counter`) using `http.Handle`.
```go
import "net/http"
...
ctr := new(Counter)
http.Handle("/counter", ctr)
```
--------------------------------
### Go: Numeric Formatting with Type Inference
Source: https://go.dev/doc/effective_go/index
Shows how Go's fmt package infers numeric types for formatting without explicit flags like signedness or size. It uses %d for decimal and %x for hexadecimal representation. The example demonstrates formatting a uint64 and its int64 equivalent.
```Go
var x uint64 = 1<<64 - 1
fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))
```
--------------------------------
### Go Defer with Loop and LIFO Execution
Source: https://go.dev/doc/effective_go/index
Illustrates how defer statements within a loop are executed in Last-In, First-Out (LIFO) order when the function returns. This behavior can be unexpected if not properly understood, as seen in the example where numbers are printed in reverse.
```go
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
// The function will return here, triggering the deferred calls.
}
// Expected output: 4 3 2 1 0
```
--------------------------------
### Go Getter and Setter Example
Source: https://go.dev/doc/effective_go/index
Illustrates idiomatic Go getter and setter methods. Getters are named after the exported field (e.g., Owner for an unexported 'owner' field), and setters follow a similar pattern (e.g., SetOwner).
```go
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
```
--------------------------------
### Go Panic Example: Cube Root Calculation Failure
Source: https://go.dev/doc/effective_go/index
Demonstrates using 'panic' in Go when a calculation, like finding the cube root using Newton's method, fails to converge after a large number of iterations. This indicates an unexpected and unrecoverable state within the function.
```Go
package main
import (
"fmt"
"math"
)
func veryClose(a, b float64) bool {
return math.Abs(a-b) < 1e-9
}
// A toy implementation of cube root using Newton's method.
func CubeRoot(x float64) float64 {
z := x/3 // Arbitrary initial value
for i := 0; i < 1e6; i++ {
prevz := z
z -= (z*z*z-x) / (3*z*z)
if veryClose(z, prevz) {
return z
}
}
// A million iterations has not converged; something is wrong.
panic(fmt.Sprintf("CubeRoot(%g) did not converge", x))
}
func main() {
// Example usage (will panic if CubeRoot doesn't converge)
// fmt.Println(CubeRoot(27))
}
```
--------------------------------
### Launch Goroutine with Function Literal (Go)
Source: https://go.dev/doc/effective_go/index
Demonstrates starting a goroutine using an anonymous function literal (closure). This is useful for performing tasks like delays or background operations. The `go` keyword initiates the concurrent execution, and the parentheses `()` immediately invoke the literal function. Variables referenced by the closure are guaranteed to persist as long as the goroutine is active.
```Go
func Announce(message string, delay time.Duration) {
go func() {
time.Sleep(delay)
fmt.Println(message)
}() // Note the parentheses - must call the function.
}
```
--------------------------------
### Run-time Interface Check for Information (Go)
Source: https://go.dev/doc/effective_go/index
This example demonstrates using the blank identifier in a type assertion to check if a value implements an interface without needing to use the asserted value itself. This is often used for conditional logic or error checking.
```go
if _, ok := val.(json.Marshaler); ok {
fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
}
```
--------------------------------
### Go Named Result Parameters for Clarity
Source: https://go.dev/doc/effective_go/index
Demonstrates using named result parameters in Go functions to enhance code readability and simplify return statements. The `nextInt` function is refactored to name its return values (`value`, `nextPos`). An example of `io.ReadFull` using named results effectively is also provided.
```go
func nextInt(b []byte, pos int) (value, nextPos int) {
}
```
```go
func ReadFull(r Reader, buf []byte) (n int, err error) {
for len(buf) > 0 && err == nil {
var nr int
nr, err = r.Read(buf)
n += nr
buf = buf[nr:]
}
return
}
```
--------------------------------
### Go Function Returning Multiple Values
Source: https://go.dev/doc/effective_go/index
Illustrates Go's capability for functions to return multiple values, which is useful for returning both a result and an error, or multiple pieces of related data. The first example shows a `Write` method signature, while the second provides a `nextInt` function that returns a parsed integer and the next position in a byte slice.
```go
func (file *File) Write(b []byte) (n int, err error) {
}
```
```go
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
```
```go
for i := 0; i < len(b) {
x, i = nextInt(b, i)
fmt.Println(x)
}
```
--------------------------------
### Create Channels in Go
Source: https://go.dev/doc/effective_go/index
Demonstrates how to create unbuffered and buffered channels in Go using the `make` function. Unbuffered channels have a default capacity of 0, while buffered channels can be initialized with a specified capacity.
```go
ci := make(chan int) // unbuffered channel of integers
ci := make(chan int, 0) // unbuffered channel of integers
cs := make(chan *os.File, 100) // buffered channel of pointers to Files
```
--------------------------------
### Initialize and Declare Go Maps
Source: https://go.dev/doc/effective_go/index
Demonstrates how to declare and initialize maps in Go using composite literal syntax with key-value pairs. Maps associate keys of comparable types with element values.
```go
var timeZone = map[string]int{
"UTC": 0*60*60,
"EST": -5*60*60,
"CST": -6*60*60,
"MST": -7*60*60,
"PST": -8*60*60,
}
```
--------------------------------
### Get User-Specified Max Procs in Go
Source: https://go.dev/doc/effective_go/index
Retrieves the user-specified number of cores that a Go program can run simultaneously using `runtime.GOMAXPROCS(0)`. This respects user configuration and environment variables.
```go
var numCPU = runtime.GOMAXPROCS(0)
```
--------------------------------
### Go Web Server for QR Code Generation
Source: https://go.dev/doc/effective_go/index
This Go program sets up an HTTP server that listens on a specified address. It handles requests to the root path by executing an HTML template, which in turn calls the Google Chart API to generate a QR code based on user input. Dependencies include the 'flag', 'html/template', 'log', and 'net/http' packages.
```Go
package main
import (
"flag"
"html/template"
"log"
"net/http"
)
var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18
var templ = template.Must(template.New("qr").Parse(templateStr))
func main() {
flag.Parse()
http.Handle("/", http.HandlerFunc(QR))
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func QR(w http.ResponseWriter, req *http.Request) {
templ.Execute(w, req.FormValue("s"))
}
const templateStr = `
QR Link Generator
{{if .}}
{{.}}
{{end}}
`
```
--------------------------------
### Go Semicolon Insertion Rules Example
Source: https://go.dev/doc/effective_go/index
Illustrates Go's automatic semicolon insertion, which occurs after tokens like identifiers, literals, and specific keywords. Semicolons can be omitted before closing braces.
```go
go func() {
for {
dst <- <-src
}
}()
```
--------------------------------
### Go Initializing a Slice of Byte Slices
Source: https://go.dev/doc/effective_go/index
Demonstrates initializing a 'LinesOfText' type, which is a slice of byte slices. Each inner byte slice can have a different length, representing lines of text.
```go
text := LinesOfText{
[]byte("Now is the time"),
[]byte("for all good gophers"),
[]byte("to bring some fun to the party."),
}
```
--------------------------------
### Get Number of Hardware CPU Cores in Go
Source: https://go.dev/doc/effective_go/index
Retrieves the number of hardware CPU cores available on the machine using the `runtime.NumCPU` function. This is useful for determining the optimal number of parallel tasks.
```go
var numCPU = runtime.NumCPU()
```
--------------------------------
### Go log.Println Implementation with fmt.Sprintln
Source: https://go.dev/doc/effective_go/index
Shows the implementation of log.Println, which forwards its variadic arguments directly to fmt.Sprintln for actual formatting and output. The '...' syntax is crucial for passing slice elements as individual arguments.
```go
// Println prints to the standard logger in the manner of fmt.Println.
func Println(v ...interface{}) {
std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string)
}
```
--------------------------------
### Implement and Register Function-Based HTTP Handler in Go
Source: https://go.dev/doc/effective_go/index
Demonstrates how to create an HTTP handler from a regular function (`ArgServer`). The function is first given the correct signature and then converted to `http.HandlerFunc` to be registered with `http.Handle`.
```go
// Argument server.
func ArgServer(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, os.Args)
}
http.Handle("/args", http.HandlerFunc(ArgServer))
```
--------------------------------
### Go Defining 2D Slice Types
Source: https://go.dev/doc/effective_go/index
Examples of defining types that represent two-dimensional data structures using Go's slice capabilities. 'Transform' is an array of arrays, while 'LinesOfText' is a slice of byte slices.
```go
type Transform [3][3]float64 // A 3x3 array, really an array of arrays.
type LinesOfText [][]byte // A slice of byte slices.
```
--------------------------------
### Go Control Structure Brace Placement
Source: https://go.dev/doc/effective_go/index
Demonstrates the correct placement of braces for control structures in Go. The opening brace must be on the same line as the control statement to avoid incorrect semicolon insertion.
```go
if i < f() {
g()
}
```
```go
if i < f() // wrong!
{
g()
}
```
--------------------------------
### Type Assertion to Extract String Value
Source: https://go.dev/doc/effective_go/index
Shows a type assertion to extract a string value from an interface{}. This is a direct way to get a specific type if you are certain of its presence, but can cause a panic if the type doesn't match.
```Go
str := value.(string)
```
--------------------------------
### Go: String and Byte Slice Formatting with %q and %#q
Source: https://go.dev/doc/effective_go/index
Explains the use of %q for quoted string representation and %#q for backquoted representation of strings or byte slices. It also mentions %q's applicability to integers and runes.
```Go
fmt.Printf("%q\n", "abc\tdef")
fmt.Printf("%#q\n", "abc\tdef")
```
--------------------------------
### Job Struct Embedding log.Logger in Go
Source: https://go.dev/doc/effective_go/index
This example shows embedding a *log.Logger within a Job struct. This grants the Job type all methods of *log.Logger (like Println, Printf), simplifying logging operations for Job instances.
```go
type Job struct {
Command string
*log.Logger
}
```
--------------------------------
### Go Variable Initialization from Environment
Source: https://go.dev/doc/effective_go/index
Illustrates initializing global variables in Go using values from environment variables. The `os.Getenv` function retrieves environment variable values at run time. This is common for configuration settings.
```go
var (
home = os.Getenv("HOME")
user = os.Getenv("USER")
gopath = os.Getenv("GOPATH")
)
```
--------------------------------
### Gate Goroutine Creation with Channels in Go
Source: https://go.dev/doc/effective_go/index
Demonstrates a pattern to manage resource consumption by gating the creation of goroutines using a buffered channel as a semaphore. This prevents excessive goroutine spawning when requests arrive rapidly.
```go
func Serve(queue chan *Request) {
for req := range queue {
sem <- 1
go func() {
process(req)
<-sem
}()
}
}
```
--------------------------------
### Go Comparison: `new` vs. `make` for Slices
Source: https://go.dev/doc/effective_go/index
Compares the idiomatic use of `make` for slice creation with the less useful `new` function. `make` initializes the slice structure for use, while `new` returns a pointer to a zeroed, nil slice.
```go
var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
// Unnecessarily complex:
var p *[]int = new([]int)
*p = make([]int, 100, 100)
// Idiomatic:
v := make([]int, 100)
```
--------------------------------
### Go: Struct and Map Formatting with %v, %+v, %#v
Source: https://go.dev/doc/effective_go/index
Demonstrates different formatting options for structs and maps using fmt.Printf. '%v' provides the default representation, '%+v' includes field names for structs, and '%#v' prints the value in Go syntax.
```Go
type T struct {
a int
b float64
c string
}
t := &T{ 7, -2.35, "abc\tdef" }
fmt.Printf("%v\n", t)
fmt.Printf("%+v\n", t)
fmt.Printf("%#v\n", t)
fmt.Printf("%#v\n", timeZone)
```
--------------------------------
### Implement Sets using Go Maps
Source: https://go.dev/doc/effective_go/index
Illustrates how to use a map with boolean values to implement a set. Presence in the map indicates membership in the set.
```go
attended := map[string]bool{
"Ann": true,
"Joe": true,
...
}
if attended[person] { // will be false if person is not in the map
fmt.Println(person, "was at the meeting")
}
```
--------------------------------
### Go Allocation with `make` for Slice
Source: https://go.dev/doc/effective_go/index
Illustrates the use of the `make` built-in function to allocate and initialize a slice with a specified length and capacity. This is the idiomatic way to create slices that need specific dimensions.
```go
make([]int, 10, 100)
```
--------------------------------
### Go 'for...range' Loop with Key and Value
Source: https://go.dev/doc/effective_go/index
Shows how to iterate over maps, slices, arrays, strings, or channels using the 'range' clause, simultaneously providing both the key (or index) and the value for each element.
```Go
for key, value := range oldMap {
newMap[key] = value
}
```
--------------------------------
### Go Composite Literals for Arrays, Slices, Maps
Source: https://go.dev/doc/effective_go/index
Demonstrates the creation of composite literals for arrays, slices, and maps using indices or keys for initialization. The initializations are independent of specific constant values as long as they are distinct.
```go
a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
```
--------------------------------
### Client Request and Response Handling in Go RPC
Source: https://go.dev/doc/effective_go/index
Illustrates how a client sends a request containing data, a function, and a result channel, and then waits for the response. This showcases the interaction pattern with the server.
```go
func sum(a []int) (s int) {
for _, v := range a {
s += v
}
return
}
request := &Request{[]int{3, 4, 5}, sum, make(chan int)}
// Send request
clientRequests <- request
// Wait for response.
fmt.Printf("answer: %d\n", <-request.resultChan)
```
--------------------------------
### Implement HTTP Handler with a Channel in Go
Source: https://go.dev/doc/effective_go/index
An HTTP handler implementation using a channel (`Chan`) that sends a notification on each visit. The `ServeHTTP` method sends the request pointer to the channel and responds with a confirmation message.
```go
// A channel that sends a notification on each visit.
// (Probably want the channel to be buffered.)
type Chan chan *http.Request
func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ch <- req
fmt.Fprint(w, "notification sent")
}
```
--------------------------------
### Go Min Function with Variadic Integers
Source: https://go.dev/doc/effective_go/index
Illustrates a variadic function 'Min' that accepts a variable number of integers ('...int') and returns the smallest among them. It initializes 'min' to the largest possible integer value.
```go
func Min(a ...int) int {
min := int(^uint(0) >> 1) // largest int
for _, i := range a {
if i < min {
min = i
}
}
return min
}
```
--------------------------------
### Go 'for' Loop Variations
Source: https://go.dev/doc/effective_go/index
Demonstrates the three fundamental forms of the 'for' loop in Go: the C-style 'for' with initialization, condition, and post-statement; the C-style 'while' loop; and the infinite 'for' loop.
```Go
// Like a C for
for init; condition; post { }
// Like a C while
for condition { }
// Like a C for(;;)
for { }
```
--------------------------------
### Go Printf Function Signature
Source: https://go.dev/doc/effective_go/index
Demonstrates the signature of the Printf function, which accepts a format string and a variable number of arguments of any type using '...interface{}'. This allows for flexible printing capabilities.
```go
func Printf(format string, v ...interface{}) (n int, err error) {
```
--------------------------------
### Go: Custom Type String Formatting with String() Method
Source: https://go.dev/doc/effective_go/index
Shows how to define a String() string method on a custom type to control its default string representation when used with fmt.Print and fmt.Printf("%v").
```Go
type T struct {
a int
b float64
c string
}
func (t *T) String() string {
return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
}
// Example usage:
t := &T{ 7, -2.35, "abc\tdef" }
fmt.Printf("%v\n", t)
```
--------------------------------
### Go Reading a Buffer Byte by Byte
Source: https://go.dev/doc/effective_go/index
An alternative method to read the first 32 bytes of a buffer by repeatedly reading one byte at a time. This approach is less efficient than direct slicing but illustrates manual buffer manipulation.
```go
var n int
var err error
for i := 0; i < 32; i++ {
nbytes, e := f.Read(buf[i:i+1]) // Read one byte.
n += nbytes
if nbytes == 0 || e != nil {
err = e
break
}
}
```
--------------------------------
### Format Go struct with `gofmt`
Source: https://go.dev/doc/effective_go/index
Demonstrates how the `gofmt` tool automatically formats Go struct declarations, specifically aligning comments for better readability. It takes an unformatted struct and shows the output after applying `gofmt`.
```go
type T struct {
name string // name of the object
value int // its value
}
```
```go
type T struct {
name string // name of the object
value int // its value
}
```
--------------------------------
### Go Defer for Tracing Function Execution
Source: https://go.dev/doc/effective_go/index
Shows a more practical use of the defer statement for tracing function entry and exit. Arguments to deferred functions are evaluated when `defer` is executed, allowing for dynamic tracing information.
```go
package main
import "fmt"
func trace(s string) string {
fmt.Println("entering:", s)
return s
}
func un(s string) {
fmt.Println("leaving:", s)
}
func a() {
defer un(trace("a"))
fmt.Println("in a")
}
func b() {
defer un(trace("b"))
fmt.Println("in b")
a()
}
func main() {
b()
}
/*
Expected output:
entering: b
in b
entering: a
in a
leaving: a
leaving: b
*/
```
--------------------------------
### Go Constants with Iota Enumeration
Source: https://go.dev/doc/effective_go/index
Demonstrates the use of iota to create enumerated constants in Go. Constants are declared at compile time and can be numbers, characters, strings, or booleans. Iota simplifies the creation of sequential values.
```go
type ByteSize float64
const (
_ ByteSize = iota // ignore first value
KB
MB
GB
TB
PB
EB
ZB
YB
)
```
--------------------------------
### Go 'for...range' with Unicode Characters
Source: https://go.dev/doc/effective_go/index
Explains and demonstrates how the 'range' clause on a string iterates over Unicode code points (runes), correctly handling UTF-8 encoding, including erroneous sequences.
```Go
for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
fmt.Printf("character %#U starts at byte position %d\n", char, pos)
}
```
--------------------------------
### Synchronize Goroutines with Channels in Go
Source: https://go.dev/doc/effective_go/index
Illustrates how to use a channel to synchronize the completion of a goroutine. A signal is sent on the channel when the sorting task is done, and the main goroutine waits to receive this signal before proceeding.
```go
c := make(chan int) // Allocate a channel.
// Start the sort in a goroutine; when it completes, signal on the channel.
go func() {
list.Sort()
c <- 1 // Send a signal; value does not matter.
}()
doSomethingForAWhile()
<-c // Wait for sort to finish; discard sent value.
```
--------------------------------
### Importing Package for Side Effects using Blank Identifier (Go)
Source: https://go.dev/doc/effective_go/index
Explains how to import a Go package solely for its side effects, such as initialization or registration, by assigning the import path to the blank identifier. This is common for packages that set up handlers or perform background tasks.
```go
import _ "net/http/pprof"
```
--------------------------------
### Go: Type Formatting with %T
Source: https://go.dev/doc/effective_go/index
Demonstrates how to print the type of a Go value using the %T format specifier within fmt.Printf.
```Go
fmt.Printf("%T\n", timeZone)
```
--------------------------------
### Go 'switch' with Comma-Separated Cases
Source: https://go.dev/doc/effective_go/index
Illustrates how multiple cases in a Go 'switch' statement can be grouped into a single case using a comma-separated list of values, avoiding repetitive code.
```Go
func shouldEscape(c byte) bool {
switch c {
case ' ', '?', '&', '=', '#', '+', '%':
return true
}
return false
}
```
--------------------------------
### Go: Generic Value Formatting with %v
Source: https://go.dev/doc/effective_go/index
Illustrates the use of the %v format specifier for printing any Go value in its default format, equivalent to Println. This includes complex types like maps, slices, and structs.
```Go
fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone)
```
--------------------------------
### Go 'for' Loop with Parallel Assignment
Source: https://go.dev/doc/effective_go/index
Shows how to use parallel assignment in a 'for' loop's initialization and post-statement to manage multiple variables, useful for operations like reversing a slice, as Go lacks a comma operator for `++` and `--`.
```Go
// Reverse a
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
```
--------------------------------
### Implement io.Writer Method for ByteSlice (Pointer Receiver)
Source: https://go.dev/doc/effective_go/index
Illustrates implementing the 'Write' method for a 'ByteSlice' pointer receiver, satisfying the 'io.Writer' interface. This enables writing data directly into the slice, similar to bytes.Buffer.
```go
func (p *ByteSlice) Write(data []byte) (n int, err error) {
slice := *p
// Again as above.
*p = slice
return len(data), nil
}
```
--------------------------------
### Use Buffered Channels as Semaphores in Go
Source: https://go.dev/doc/effective_go/index
Shows how a buffered channel can act as a semaphore to limit the number of concurrent operations. Sending to the channel acquires a permit, and receiving from it releases a permit, effectively controlling throughput.
```go
var sem = make(chan int, MaxOutstanding)
func handle(r *Request) {
sem <- 1 // Wait for active queue to drain.
process(r) // May take a long time.
<-sem // Done; enable next request to run.
}
func Serve(queue chan *Request) {
for {
req := <-queue
go handle(req) // Don't wait for handle to finish.
}
}
```
--------------------------------
### Go 'switch' with Labeled 'break' to Exit Loop
Source: https://go.dev/doc/effective_go/index
Shows how to use a labeled 'break' statement to exit not only the current 'switch' but also a surrounding loop, useful for complex control flow within nested structures.
```Go
Loop:
for n := 0; n < len(src); n += size {
switch {
case src[n] < sizeOne:
if validateOnly {
break
}
size = 1
update(src[n])
case src[n] < sizeTwo:
if n+1 >= len(src) {
err = errShortInput
break Loop
}
if validateOnly {
break
}
size = 2
update(src[n] + src[n+1]<= YB:
return fmt.Sprintf("%.2fYB", b/YB)
case b >= ZB:
return fmt.Sprintf("%.2fZB", b/ZB)
case b >= EB:
return fmt.Sprintf("%.2fEB", b/EB)
case b >= PB:
return fmt.Sprintf("%.2fPB", b/PB)
case b >= TB:
return fmt.Sprintf("%.2fTB", b/TB)
case b >= GB:
return fmt.Sprintf("%.2fGB", b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB", b/MB)
case b >= KB:
return fmt.Sprintf("%.2fKB", b/KB)
}
return fmt.Sprintf("%.2fB", b)
}
```
--------------------------------
### Go Composite Literal Initialization
Source: https://go.dev/doc/effective_go/index
Simplifies struct initialization using a composite literal, directly creating and returning a pointer to a new struct instance. This is more concise than manual field assignment.
```go
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := File{fd, name, nil, 0}
return &f
}
```
--------------------------------
### Sequence String Method using sort.IntSlice
Source: https://go.dev/doc/effective_go/index
Demonstrates using the sort.IntSlice type to sort a Sequence before converting it to a plain []int for printing. This highlights using existing types to implement desired functionality.
```Go
type Sequence []int
// Method for printing - sorts the elements before printing
func (s Sequence) String() string {
s = s.Copy()
sort.IntSlice(s).Sort()
return fmt.Sprint([]int(s))
}
```