How About Go Language?
Well-written Go programs tend to be straightforward and sometimes a bit repetitive. There’s no inheritance, no aspect-oriented programming, no function overloading, and certainly no operator overloading. There’s no pattern matching, no named parameters, no exceptions.
Setting Up Go Environment
Installing Go
Archlinux
|
|
Mac
|
|
Windows
|
|
Verify installed Go:
|
|
The Go Workspace
environment variables:
-
$GOROOTGOROOT is a variable that defines where your Go SDK is located. You do not need to change this variable, unless you plan to use different Go versions.
-
$GOPATHGOPATH is a variable that defines the root of your workspace. By default, the workspace directory is a directory that is named
gowithin your user home directory ($HOME/go for Linux and macOS, %USERPROFILE%/go for Windows). GOPATH stores your code base and all the files that are necessary for your development. GOPATH is the root of your workspace and contains the following folders:- src/: location of Go source code (for example, .go, .c, .g, .s).
- pkg/: location of compiled package code (for example, .a).
- bin/: location of compiled executable programs built by Go.
-
$GOBINThe directory where executables are installed using the go command. By default,
$GOBINis$GOPATH/bin(or$HOME/go/binifGOPATHis not set). After installing, you will want to add this directory to your$PATHso you can use installed tools.
It’s a good idea to explicitly define GOPATH and to put the $GOPATH/bin directory in executable path makes it easier to run third-party tools installed via go install.
|
|
The go Command
Print Go environment information:
|
|
To unset a variable
|
|
Compile and run Go program:
|
|
Compile packages and dependencies:
|
|
Add dependencies to current module and install them:
|
|
Get resolves its command-line arguments to packages at specific module versions, updates go.mod to require those versions, and downloads source code into the module cache. Now, ‘go get’ is dedicated to adjusting dependencies in go.mod.
Compile and install packages and dependencies:
|
|
Executables are installed in the directory named by the GOBIN environment variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH environment variable is not set. Executables in $GOROOT are installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN.
When a version is specified, ‘go install’ runs in module-aware mode and ignores the go.mod file in the current directory.
Gofmt (reformat) package sources:
|
|
There’s an enhanced version of go fmt available called goimports that also cleans up your import statements.
|
|
|
|
List packages or modules:
|
|
Report likely mistakes in packages:
|
|
Module maintenance:
initialize new module in current directory
|
|
add missing and remove unused modules
|
|
download modules to local cache
|
|
Remove object files and cached files:
|
|
remove all downloaded modules, including unpacked source code of versioned dependencies.
|
|
Test packages:
|
|
Linting
Linting:
|
|
|
|
golangci-lint combines go lint, go vet, and an ever-increasing set of other code quality tools. Once it is installed, you run golangci-lint with the command:
|
|
Tools
-
Visual Studio Code
extension tools: The Delve debugger, and gopls
-
Goland
|
|
Makefiles
GOPROXY
Installation
|
|
Go 1.13 and above (RECOMMENDED)
|
|
|
|
macOS or Linux
|
|
|
|
Windows
|
|
|
|
Alternative Proxy
|
|
Lexical elements
Comments
|
|
Semicolons
The Semicolon Insertion Rule:
The lexer uses a simple rule to insert semicolons automatically:
-
If the last token before a newline is an identifier (which includes words like
intandfloat64), a basic literal such as a number or string constant, or one of the tokens1break continue fallthrough return ++ -- ) }the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.
-
A semicolon can also be omitted immediately before a closing brace, so a statement such as
1go func() { for { dst <- <-src } }()
needs no semicolons.
One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line.
|
|
|
|
literals
Literals in Go are untyped, they can interact with any variable that’s compatible with the literal.
|
|
Primitive Types
Boolean
Variables of bool type can have one of two predeclared constant values: true or false.
|
|
Numeric
|
|
|
|
The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.
Explicit conversions are required when different numeric types are mixed in an expression or assignment.
Using int64 and uint64 in a library function and let callers use type conversions to pass values in. In those cases, you need to write a separate function for every integer type.
The result of an integer division is an integer; if you want to get a floating point result, you need to use a type conversion to make your integers into floating point numbers.
Arithmetic operators:
|
|
Operators with assignment statements:
|
|
Go has integer types called byte and rune that are aliases for uint8 and int32 data types, respectively. In Go, there is no char data type. It uses byte and rune to represent character values. The byte data type represents ASCII characters while the rune data type represents a more broader set of Unicode characters that are encoded in UTF-8 format.
The default type for character values is rune, which means, if we don’t declare a type explicitly when declaring a variable with a character value, then Go will infer the type as rune.
|
|
String
Strings are immutable: once created, it is impossible to change the contents of a string.
|
|
Zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
0for numeric types,falsefor the boolean type, and""(the empty string) for strings.
Type conversions
The expression T(v) converts the value v to the type T.
|
|
Unlike in C, in Go assignment between items of different type requires an explicit conversion.
An explicit conversion is an expression of the form T(x) where T is a type and x is an expression that can be converted to type T.
|
|
|
|
If the type starts with the operator * or <-, or if the type starts with the keyword func and has no result list, it must be parenthesized when necessary to avoid ambiguity:
|
|
Another Go type cannot be treated as a boolean. In fact, no other type can be converted to a bool, implicitly or explicitly. If you want to convert from another data type to boolean, you must use one of the comparison operators (==, !=, >, <, <=, or >=). For example, to check if variable x is equal to 0, the code would be x == 0. If you want to check if string s is empty, use s == “”.
Variables
Variables
The var statement declares a list of variables; as in function argument lists, the type is last.
|
|
Variables with initializers
If an initializer is present, the type can be omitted
|
|
Short variable declarations
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
Outside a function, every statement begins with a keyword (var, func, and so on) and so the :=construct is not available.
A variable is a storage location for holding a value. Go assigns a zero value (default value) to any variable that is declared but not assigned a value.
|
|
If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first implicitly converted to its default type; if it is an untyped boolean value, it is first implicitly converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.
|
|
Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.
Short variable declarations
A short variable declaration uses the syntax:
|
|
Unlike regular variable declarations, a short variable declaration may redeclare variables with the same type.
Short variable declarations may appear only inside functions. Declaring a variable at package level, must use var.
Package-level variables whose values change are a bad idea. As a general rule, only declare variables in the package block that are effectively immutable.
It is an error to declare a variable without using it. The blank identifier provides a workaround.
|
|
Type inference
When declaring a variable without specifying an explicit type, the variable’s type is inferred from the value on the right hand side.
When the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:
|
|
Constant
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.
There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.
Typed Constants
Numeric constants are high-precision values.
|
|
Untyped Constants
An untyped constant takes the type needed by its context.
If you are giving a name to a mathematical constant that could be used with multiple numeric types, then keep the constant untyped.
If the expression values are untyped constants, the declared constants remain untyped and the constant identifiers denote the constant values.
|
|
const in Go is very limited. Constants in Go are a way to give names to literals. They can only hold values that the compiler can figure out at compile time. Go doesn’t provide a way to specify that a value calculated at runtime is immutable.
Naming
Go requires identifier names to start with a letter or underscore, and the name can contain numbers, underscores, and letters.
Package names
By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps.
Don’t use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.
Getters
If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner.
|
|
Interface names
By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.
If your type implements a method with the same meaning as a method on a well-known type, give it the same name and signature; call your string-converter method String not ToString.
Constants names
In many languages, constants are always written in all uppercase letters, with words separated by underscores. Go does not follow this pattern. This is because Go uses the case of the first letter in the name of a package-level declaration to determine if the item is accessible outside the package.
MixedCaps
The convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names.
People will use the first letter of a type as the variable name (for example, i for integers, f for floats, b for -booleans). When you define your own types, similar patterns apply.
Composite Types
Pointers
Go has pointers. A pointer holds the memory address of a value.
The type *T is a pointer to a T value. Its zero value is nil.
|
|
|
|
The * operator denotes the pointer’s underlying value. This is known as “dereferencing” or “indirecting”.
|
|
Unlike C, Go has no pointer arithmetic.
Pointer references to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil.
Reference:
For an operand x of type T, the address operation &x generates a pointer of type *T to x.
Dereference
* is also used to dereference pointer variables.
Array
The type [n]T is an array of n values of type T.
|
|
Arrays cannot be resized.
Slices
Strings and Runes and Bytes
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array.
The type []T is a slice with elements of type T.
A slice is formed by specifying two indices, a low and high bound, separated by a colon, which is a half-open range:
|
|
Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.
Changing the elements of a slice modifies the corresponding elements of its underlying array.
Slice literals
A slice literal is like an array literal without the length.
This creates an array, then builds a slice that references it:
|
|
Slice defaults
When slicing, you may omit the high or low bounds to use their defaults instead.
The default is zero for the low bound and the length of the slice for the high bound.
Slice length and capacity
A slice has both a length and a capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).
You can extend a slice’s length by re-slicing it, provided it has sufficient capacity.
Nil slices
The zero value of a slice is nil.
A nil slice has a length and capacity of 0 and has no underlying array.
Creating a slice with make
Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.
The make function allocates a zeroed array and returns a slice that refers to that array:
|
|
To specify a capacity, pass a third argument to make:
|
|
Slices of slices
Slices can contain any type, including other slices.
|
|
Appending to a slice
It is common to append new elements to a slice, and so Go provides a built-in append function.
|
|
|
|
Range
The range form of the for loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
Range continued
You can skip the index or value by assigning to _.
|
|
Exercise: Slices
|
|
Maps
A map maps keys to values.
The zero value of a map is nil. A nil map has no keys, nor can keys be added.
The make function returns a map of the given type, initialized and ready for use.
|
|
Map literals
Map literals are like struct literals, but the keys are required.
|
|
Map literals continued
If the top-level type is just a type name, you can omit it from the elements of the literal.
|
|
Mutating Maps
|
|
Test that a key is present with a two-value assignment:
|
|
If key is in m, ok is true. If not, ok is false.
If key is not in the map, then elem is the zero value for the map’s element type.
Exercise: Maps
|
|
Structs
A struct is a collection of fields.
|
|
Struct Fields
Struct fields are accessed using a dot.
|
|
Pointers to structs
Struct fields can be accessed through a struct pointer. The language permits us instead to write just p.X, without the explicit dereference.
Struct Literals
A struct literal denotes a newly allocated struct value by listing the values of its fields. You can list just a subset of fields by using the Name:syntax.
The special prefix & returns a pointer to the struct value.
|
|
Function
Interface
Map
Channel
Control Flow
For
Go has only one looping construct, the for loop.
Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.
|
|
The init and post statements are optional.
|
|
For is Go’s “while”
|
|
Forever
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
|
|
If
Go’s if statements need not be surrounded by parentheses ( ) but the braces { } are required.
|
|
If with a short statement
The if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if.
|
|
If and else
Variables declared inside an if short statement are also available inside any of the else blocks.
|
|
Switch
A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.
Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case in other languages is provided automatically in Go. Another important difference is that Go’s switch cases need not be constants, and the values involved need not be integers.
|
|
Switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
Switch with no condition
Switch without a condition is the same as switch true.
This construct can be a clean way to write long if-then-else chains.
|
|
Defer
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
|
|
Stacking defers
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
Functions
Function values
Functions are values too. They can be passed around just like other values.
Function values may be used as function arguments and return values.
|
|
Function closures
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.
|
|
Exercise: Fibonacci closure
|
|
A function can take zero or more arguments. Notice that the type comes after the argument name.
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
|
|
Multiple results
A function can return any number of results.
|
|
Named return values
Go’s return values may be named. These names should be used to document the meaning of the return values.
A return statement without arguments returns the named return values. This is known as a “naked” return.
Naked return statements should be used only in short functions. They can harm readability in longer functions.
|
|
Methods
A method is a function with a receiver. A method declaration associates the method with the receiver’s base type.
The receiver type must be a defined type T or a pointer to a defined type T.
|
|
Go does not have classes. However, you can define methods on types.
A method is a function with a special receiver argument.
The receiver appears in its own argument list between the func keyword and the method name.
|
|
Methods are functions
Remember: a method is just a function with a receiver argument.
|
|
You can declare a method on non-struct types, too.
You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).
|
|
Pointer receivers
You can declare methods with pointer receivers.
This means the receiver type has the literal syntax *T for some type T. (Also, T cannot itself be a pointer such as *int.)
For example, the Scale method here is defined on *Vertex.
Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are more common than value receivers.
With a value receiver, the method operates on a copy of the original value.
|
|
Pointers and functions
The Abs and Scale methods rewritten as functions.
|
|
Methods and pointer indirection
Comparing the previous two programs, you might notice that functions with a pointer argument must take a pointer:
|
|
while methods with pointer receivers take either a value or a pointer as the receiver when they are called:
|
|
For the statement v.Scale(5), even though v is a value and not a pointer, the method with the pointer receiver is called automatically. That is, as a convenience, Go interprets the statement v.Scale(5) as (&v).Scale(5) since the Scale method has a pointer receiver.
Methods and pointer indirection (2)
The equivalent thing happens in the reverse direction.
|
|
Functions that take a value argument must take a value of that specific type:
|
|
while methods with value receivers take either a value or a pointer as the receiver when they are called:
|
|
In this case, the method call p.Abs() is interpreted as (*p).Abs().
Choosing a value or pointer receiver
There are two reasons to use a pointer receiver.
The first is so that the method can modify the value that its receiver points to.
The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct.
In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
Interfaces
An interface type is defined as a set of method signatures.
A value of interface type can hold any value that implements those methods.
|
|
Interfaces are implemented implicitly
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.
Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.
Interface values
Under the hood, interface values can be thought of as a tuple of a value and a concrete type:
|
|
An interface value holds a value of a specific underlying concrete type.
Calling a method on an interface value executes the method of the same name on its underlying type.
Interface values with nil underlying values
If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.
In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)
Note that an interface value that holds a nil concrete value is itself non-nil.
|
|
Nil interface values
A nil interface value holds neither value nor concrete type.
Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.
|
|
The empty interface
The interface type that specifies zero methods is known as the empty interface:
|
|
An empty interface may hold values of any type. (Every type implements at least zero methods.)
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Printtakes any number of arguments of type interface{}.
|
|
Type assertions
A type assertion provides access to an interface value’s underlying concrete value.
|
|
This statement asserts that the interface value iholds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
|
|
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
Note the similarity between this syntax and that of reading from a map.
examples:
|
|
Type switches
A type switch is a construct that permits several type assertions in series.
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
|
|
The declaration in a type switch has the same syntax as a type assertion i.(T), but the specific type T is replaced with the keyword type.
This switch statement tests whether the interface value i holds a value of type T or S. In each of the T and S cases, the variable v will be of type T or S respectively and hold the value held by i. In the default case (where there is no match), the variable v is of the same interface type and value as i.
Stringers
One of the most ubiquitous interfaces is Stringer defined by the fmt package.
|
|
A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.
Exercise: Stringers
Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.
|
|
Errors
Go programs express error state with error values.
The error type is a built-in interface similar to fmt.Stringer:
|
|
(As with fmt.Stringer, the fmt package looks for the error interface when printing values.)
**Functions often return an error value, and calling code should handle errors by testing whether the error equals nil**.
|
|
A nil error denotes success; a non-nil error denotes failure.
|
|
Exercise: Errors
|
|
Readers
The io package specifies the io.Reader interface, which represents the read end of a stream of data.
The Go standard library contains many implementations of these interfaces, including files, network connections, compressors, ciphers, and others.
The io.Reader interface has a Read method:
|
|
Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.
|
|
Exercise: Readers
Implement a Reader type that emits an infinite stream of the ASCII character 'A'.
|
|
Exercise: rot13Reader
A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way.
For example, the gzip.NewReader function takes an io.Reader (a stream of compressed data) and returns a *gzip.Reader that also implements io.Reader (a stream of the decompressed data).
|
|
Images
Package image defines the Image interface:
|
|
Note: the Rectangle return value of the Boundsmethod is actually an image.Rectangle, as the declaration is inside package image.
(See the documentation for all the details.)
The color.Color and color.Model types are also interfaces, but we’ll ignore that by using the predefined implementations color.RGBA and color.RGBAModel. These interfaces and types are specified by the image/color package
Exercise: Images
Remember the picture generator you wrote earlier? Let’s write another one, but this time it will return an implementation of image.Image instead of a slice of data.
Define your own Image type, implement the necessary methods, and call pic.ShowImage.
Bounds should return a image.Rectangle, like image.Rect(0, 0, w, h).
ColorModel should return color.RGBAModel.
At should return a color; the value v in the last picture generator corresponds to color.RGBA{v, v, 255, 255} in this one.
|
|
Modules
Repositories, Modules, and Packages
Dependency tracking using go.mod
The go mod init command initializes and writes a new go.mod file in the current directory, in effect creating a new module rooted at the current directory.
|
|
By default, the go list command lists the packages that are used in your project. The
-m flag changes the output to list the modules instead.
|
|
go mod tidy ensures that the go.mod file matches the source code in the module. It adds any missing module requirements necessary to build the current module’s packages and dependencies, and it removes requirements on modules that don’t provide any relevant packages. It also adds any missing entries to go.sum and removes unnecessary entries.
|
|
Whenever you run any go command that requires dependencies (such as go run, go build, go test, or even go list). The go.sum will be created.
Packages
Creating a Package
The package clause consists of the keyword package and the name for the package. The package clause is always the first nonblank, noncomment line in a Go source file. It defines the package to which the file belongs.
|
|
A single unimported package called the main package is the special package to be a staring point.
By convention, the package name is the same as the last element of the import path.
Import
A package’s exported identifiers (an identifier is the name of a variable, coonstant, type, function, method, or a field in a struct) cannot be accessed from another current package without an import statement.
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
- the first character of the identifier’s name is a Unicode uppercase letter (Unicode character category Lu); and
- the identifier is declared in the package block or it is a field name or method name.
The import path must be specified when importing from anywhere besides the standard library. The import path is built by appending the path to the package within the module to the module path. By convention, the package name is the same as the last element of the import path.
How exported identifiers is accessed for the various types of import declaration:
|
|
To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:
|
|
It is good style to use the factored import statement:
|
|
Call code in an external package
- Visit pkg.go.dev and search package, such as quote
- Locate and click selection package
- note that package
quoteis included in thersc.io/quotemodule
|
|
Input and Output
Goroutines and Channels
concurrent progrmming model: CSP (communicationg sequential processes)
Goroutines
A goroutine is a lightweight thread managed by the Go runtime.
|
|
starts a new goroutine running
|
|
The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.
Goroutines run in the same address space, so access to shared memory must be synchronized.
Channels
Channels are a typed conduit through which you can send and receive values with the channel operator, <-.
|
|
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
|
|
Buffered Channels
Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:
|
|
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
The capacity of buffered channels can be obtained using the expressions cap().
|
|
Range and Close
A sender can close a channel to indicate that no more values will be sent.
|
|
Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after
|
|
ok is false if there are no more values to receive and the channel is closed.
The loop for i := range c receives values from the channel repeatedly until it is closed.
Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
Another note: Channels aren’t like files; you don’t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.
Select
The select statement lets a goroutine wait on multiple communication operations.
A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
|
|
Default Selection
The default case in a select is run if no other case is ready. Use a default case to try a send or receive without blocking
|
|
Concurrency with Shared Variables
concurrent progrmming model: shared memory multithreading
sync.Mutex
Make sure only one goroutine can access a variable at a time to avoid conflicts. This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex.
Go’s standard library provides mutual exclusion with sync.Mutex and its two methods:
LockUnlock
Use defer to ensure the mutex will be unlocked.
|
|
Reflection
FieldByName
|
|
What Now?
You can get started by installing Go.
Once you have Go installed, the Go Documentation is a great place to continue. It contains references, tutorials, videos, and more.
To learn how to organize and work with Go code, read How to Write Go Code.
If you need help with the standard library, see the package reference. For help with the language itself, you might be surprised to find the Language Spec is quite readable.
To further explore Go’s concurrency model, watch Go Concurrency Patterns (slides) and Advanced Go Concurrency Patterns (slides) and read the Share Memory by Communicating codewalk.
To get started writing web applications, watch A simple programming environment (slides) and read the Writing Web Applications tutorial.
The First Class Functions in Go codewalk gives an interesting perspective on Go’s function types.
The Go Blog has a large archive of informative Go articles.
Visit the Go home page for more.
Reference
The Go Programming Language Specification
generate-model-structs-from-database
go-get-golang-x-solution.md
good-at.md
gorm.md
modules.md
photoprism.md