
Golang Spec is a specification for the Go programming language that provides a clear and concise definition of the language's syntax and semantics. It's a must-know for any Go developer.
The Golang Spec is divided into several sections, including the "Spec" section, which covers the language's syntax, and the "Package" section, which covers the language's package system.
The Spec section is the core of the Golang Spec, and it's where you'll find the language's syntax rules, such as the rules for declaring variables, functions, and types.
Go's syntax is designed to be simple and easy to read, with a focus on readability and maintainability.
See what others are reading: Install Golang Package
Consider reading: 3d Ultrasound
Syntax and Notation
The Go language uses a variant of Extended Backus-Naur Form (EBNF) to specify its syntax. This notation is used to describe the language's structure and rules.
In EBNF, productions are expressions constructed from terms and specific operators. These operators, in increasing precedence, are used to define the language's syntax. Lowercase production names are used to identify lexical tokens, while non-terminals are in CamelCase.
Lexical tokens are enclosed in double quotes or back quotes. The notation a…b represents a set of characters from a to b as alternatives. The horizontal ellipsis is also used elsewhere in the spec to denote enumerations or code snippets that aren't further specified.
Notation
The notation in the Go language is specified using a variant of Extended Backus-Naur Form (EBNF). This is a formal way to describe the syntax of the language.
EBNF uses productions, which are expressions constructed from terms and operators. These operators have a specific precedence, with lowercase production names used for lexical tokens and non-terminals in CamelCase.
Lexical tokens are enclosed in double quotes or back quotes, which help distinguish them from other parts of the syntax. The character set a…b represents the set of characters from a through b as alternatives.
The horizontal ellipsis … is used in the spec to denote various enumerations or code snippets, but it's not a token of the Go language. This notation helps to clarify the syntax and make it easier to understand.
A link in the form [Go 1.xx] indicates that a language feature was changed or added with language version 1.xx, and thus requires at minimum that language version to build.
A fresh viewpoint: Go vs Golang
Punctuation
Punctuation is an essential part of Go's syntax, and understanding how it works can make a big difference in your coding experience.
The lexer in Go uses a simple rule to insert semicolons automatically as it scans the input text. This means that most of the time, you won't need to include semicolons in your code.
If the last token before a newline is an identifier, a basic literal, or one of the tokens ")", "]", "}", or "}", the lexer will insert a semicolon after the token.
In Go, a semicolon can be omitted immediately before a closing brace, so a statement like func main() { needs no semicolons.
Go's semicolon insertion rules also mean that you can't put the opening brace of a control structure (if, for, switch, or select) on the next line, as this would cause a semicolon to be inserted before the brace.
Here's a summary of when semicolons are inserted in Go:
By understanding how semicolons work in Go, you can write more idiomatic code and avoid common pitfalls.
Expressions
Expressions are the building blocks of code, specifying the computation of a value by applying operators and functions to operands. This is a fundamental concept in programming.
An expression can be a simple value, like a number or a string, or it can be a more complex combination of values and operators. For example, the expression 2 + 3 is a simple expression that evaluates to 5.
In Go, expressions can be used in various contexts, including function calls and receive operations. These are allowed in expression statements, which can be used in block contexts, such as within curly brackets.
The following types of expressions are allowed in expression statements: function calls (except for certain built-in functions), method calls, and receive operations.
Worth a look: Golang Function Type
Variables and Data Types
Variables in Go are storage locations for holding values, and their type determines the set of permissible values. A variable declaration reserves storage for a named variable, and its static type is the type given in its declaration.
For your interest: Golang Azure Blob Storage
Variables can be initialized with explicit values, and if a list of expressions is given, the variables are initialized with the expressions following the rules for assignment statements. Otherwise, each variable is initialized to its zero value. The zero value for a type is a default value that is assigned when storage is allocated for a variable without explicit initialization.
A variable's value is retrieved by referring to the variable in an expression, and it is the most recent value assigned to the variable. If a variable has not yet been assigned a value, its value is the zero value for its type.
Here are the types of variables in Go, along with their zero values:
- bool: false
- numeric types: 0
- strings: ""
- pointers, functions, interfaces, slices, channels, and maps: nil
Arrays, on the other hand, are values and are copied when assigned to another variable. The size of an array is part of its type, and arrays are not pointers to their underlying data.
Names
Names are as important in Go as in any other language. They even have semantic effect: the visibility of a name outside a package is determined by whether its first character is upper case.
An identifier is a sequence of one or more letters and digits. The first character in an identifier must be a letter. Some identifiers are predeclared.
The convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names. This is a good practice to follow, as it makes code more readable and easier to understand.
Predeclared identifiers are implicitly declared in the universe block. These identifiers are special and have specific meanings in the Go language. Some examples include true and false for the boolean type.
Identifiers that start with a Unicode uppercase letter are exported, meaning they can be accessed from other packages. This is a way to make code more modular and reusable. All other identifiers are not exported, which means they can only be accessed within the same package.
Here are some examples of exported identifiers:
- Reader
- Writer
- Formatter
- CloseNotifier
Note that these are just a few examples, and there are many other exported identifiers in the Go standard library.
String

String literals in Go can be expressed in two forms: raw string literals and interpreted string literals. Raw string literals are character sequences between back quotes, as in `foo`, and have no special meaning, including backslashes and newlines.
Interpreted string literals are character sequences between double quotes, as in "bar", and have the same restrictions as rune literals, including backslash escapes.
To create a string literal, you can use a combination of characters, including escape sequences, to represent a string constant. For example, the literal 'a' holds a single byte representing a literal a, Unicode U+0061, value 0x61, while 'ä' holds two bytes (0xc30xa4) representing a literal a-dieresis, U+00E4, value 0xe4.
Here are the different ways to represent an integer value as a numeric constant in a string literal:
- \x followed by exactly two hexadecimal digits
- \u followed by exactly four hexadecimal digits
- \U followed by exactly eight hexadecimal digits
- a plain backslash \ followed by exactly three octal digits
Note that octal escapes must represent a value between 0 and 255 inclusive, while hexadecimal escapes satisfy this condition by construction.
Constants
Constants in Go are created at compile time and can only be numbers, characters (runes), strings, or booleans. They are created using constant expressions, which must be evaluatable by the compiler.
Constants can be typed or untyped, with untyped constants having a default type that is implicitly converted to in contexts where a typed value is required. The default type of an untyped constant is bool, rune, int, float64, complex128, or string respectively.
A constant may be given a type explicitly by a constant declaration or conversion, or implicitly when used in a variable declaration or an assignment statement. It's an error if the constant value cannot be represented as a value of the respective type.
Implementation restrictions require that integer constants be represented with at least 256 bits, and floating-point constants with a mantissa of at least 256 bits and a signed binary exponent of at least 16 bits.
Here are the types of constants in Go:
- Boolean constants (true and false)
- Rune constants (representing single characters)
- Integer constants (representing whole numbers)
- Floating-point constants (representing decimal numbers)
- Complex constants (representing complex numbers)
- String constants (representing sequences of characters)
Constants can be used to create enumerated constants using the iota enumerator, which can be part of an expression and implicitly repeated to build intricate sets of values.
Variables
A variable is a storage location for holding a value, and its type determines the set of permissible values it can hold.
Variables can be initialized just like constants, but the initializer can be a general expression computed at run time.
A variable declaration creates one or more variables, binds corresponding identifiers to them, and gives each a type and an initial value. If a list of expressions is given, the variables are initialized with the expressions following the rules for assignment statements.
Variables can be redeclared in the same scope if the new declaration has the same type and at least one new variable is declared. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
If a variable has not yet been assigned a value, its value is the zero value for its type. The zero value for a type is a specific value that is used when no explicit value is provided, such as false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.

Variables can be initialized with a default value, which is the zero value for its type, when storage is allocated for a variable through a declaration or a call of new.
Here are the zero values for different types:
In a variable declaration, if a type is not present, 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.
Interface
An interface type defines a type set, which means a variable of interface type can store a value of any type that is in the type set of the interface.
To specify an interface type, you need to list its interface elements, which can be either methods or type elements. A type element is a union of one or more type terms, and a type term is either a single type or a single underlying type.

The value of an uninitialized variable of interface type is nil, indicating that it doesn't hold any value yet.
Interface conversions and type assertions are powerful tools in Go. A type switch is a form of conversion that takes an interface and converts it to the type of each case in the switch.
You can use a type assertion to extract a value from an interface, but be aware that if the type assertion fails, the program will crash with a run-time error.
To safely test whether a value is of a certain type, use the "comma, ok" idiom: str, ok := value.(string). If the type assertion fails, str will still exist and be of type string, but it will have the zero value, an empty string.
Here are the conditions under which a value x of type V is assignable to a variable of type T:
- V and T are identical.
- V and T have identical underlying types but are not type parameters and at least one of V or T is not a named type.
- V and T are channel types with identical element types, V is a bidirectional channel, and at least one of V or T is not a named type.
- T is an interface type, but not a type parameter, and x implements T.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type, but not a type parameter.
- x is an untyped constant representable by a value of type T.
Additionally, if x's type V or T are type parameters, x is assignable to a variable of type T if one of the following conditions applies:
- x is the predeclared identifier nil, T is a type parameter, and x is assignable to each type in T's type set.
- V is not a named type, T is a type parameter, and x is assignable to each type in T's type set.
- V is a type parameter and T is not a named type, and values of each type in V's type set are assignable to T.
Simple Slice
Slices are a fundamental concept in Go programming, and understanding how to work with them is crucial for efficient and effective coding.
A simple slice expression is used to create a substring or slice of an existing string, array, or slice. This is done by specifying the starting and ending indices of the slice.
For example, if you have a string "hello", you can create a substring "ell" by using the expression "hello[1:3]".
The indices for a simple slice expression can be omitted, with a missing low index defaulting to zero and a missing high index defaulting to the length of the sliced operand.
If the sliced operand is a pointer to an array, the expression "a[low : high]" is shorthand for "(*a)[low : high]".
For arrays or strings, the indices must be in range, meaning 0 <= low <= high <= len(a). If the indices are out of range at run time, a run-time panic occurs.
A constant index must be non-negative and representable by a value of type int.
See what others are reading: Golang String to Time
Go

Go statements in programming allow you to start the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space.
To use a Go statement, you must make a function or method call, and it cannot be parenthesized.
Built-in functions are restricted in Go statements, just like they are in expression statements.
The function value and parameters are evaluated as usual in the calling goroutine, but program execution does not wait for the invoked function to complete.
Unlike regular calls, the function begins executing independently in a new goroutine, and its execution continues until the function terminates.
If a function has any return values, they are discarded when the function completes, and the goroutine also terminates.
Intriguing read: Golang Go
Slices, Maps, Channels
Slices, maps, and channels are fundamental data types in Go that allow for efficient and flexible data manipulation.
A slice is a reference to an underlying array, and its length and capacity can be modified as long as it still fits within the limits of the underlying array. This makes slices a powerful and convenient interface to sequences of data.
Intriguing read: Golang Copy Array
A slice can be created using the built-in function make, which initializes the internal data structure and prepares the value for use. For example, make([]int, 10, 100) allocates an array of 100 ints and creates a slice structure with length 10 and a capacity of 100 pointing at the first 10 elements of the array.
Slices can also be used as arguments to functions, and changes made to the elements of the slice will be visible to the caller. This is because slices hold references to the underlying array, and if you assign one slice to another, both refer to the same array.
A map is a reference to an implementation-specific data structure, and its size can be hinted at using the make function. For example, make(map[string]int, 10) creates a map with initial space to hold 10 map elements.
Channels are also allocated with make, and the resulting value acts as a reference to an underlying data structure. Channels can be used for communication and synchronization between goroutines, and they can be unbuffered or buffered.
Here's a summary of how slices, maps, and channels are created using the make function:
By understanding how slices, maps, and channels work, you can write more efficient and effective Go code.
Address

You can get the memory address of a variable using the address operator &. This operator generates a pointer to the variable, which is a special type of variable.
The operand must be addressable, meaning it's either a variable, pointer indirection, or slice indexing operation. You can also use a field selector of an addressable struct operand or an array indexing operation of an addressable array.
For example, if you have a variable x, you can get its memory address with &x. This is useful for passing variables to functions or storing their addresses in other variables.
Pointer Indirection
You can use the pointer indirection operator * to get the value stored at a memory address. If the pointer is nil, attempting to evaluate *x will cause a run-time panic.
This is useful when you need to access the value stored at a memory address, but be careful not to use a nil pointer.
For another approach, see: Golang Use Cases

Addressability Requirements
To be addressable, a variable must meet certain requirements. It can be a variable, pointer indirection, or slice indexing operation. It can also be a field selector of an addressable struct operand or an array indexing operation of an addressable array.
A composite literal can also be addressable, even if it's not a variable. This is a special case that allows you to get the memory address of a composite literal.
Types of Addressable Variables
Here are some examples of addressable variables:
- Variables: x, y, z
- Pointer indirection: *x, *y, *z
- Slice indexing operation: mySlice[0], mySlice[1], mySlice[2]
- Field selector: myStruct.field1, myStruct.field2, myStruct.field3
- Array indexing operation: myArray[0], myArray[1], myArray[2]
- Composite literal: myCompositeLiteral
Note that this is not an exhaustive list, and there may be other types of addressable variables.
Appending and Copying Slices
Appending and copying slices is a fundamental operation in Go programming.
The built-in functions append and copy assist in common slice operations, and the result is independent of whether the memory referenced by the arguments overlaps.
The append function appends zero or more values to a slice and returns the resulting slice. If the capacity of the slice is not large enough, append allocates a new underlying array that fits both the existing slice elements and the additional values.
Consider reading: Golang Copy Slice
The function copy copies slice elements from a source to a destination and returns the number of elements copied. The number of elements copied is the minimum of len(src) and len(dst).
If the type of one or both arguments is a type parameter, all types in their respective type sets must have the same underlying slice type []E.
Here's a comparison of the append and copy functions:
Slices are a powerful and convenient interface to sequences of data. They hold references to an underlying array, and if you assign one slice to another, both refer to the same array.
A function that takes a slice argument can modify the elements of the slice, but the slice itself is passed by value. This means that after the function returns, the original slice remains unchanged.
The length of a slice may be changed as long as it still fits within the limits of the underlying array. This can be done by assigning it to a slice of itself. The capacity of a slice reports the maximum length the slice may assume.
If the data exceeds the capacity, the slice is reallocated and the resulting slice is returned.
Control Flow
Control flow in Go is a bit different from what you might be used to in other languages. The lack of do or while loops means you'll be working with for loops more often, and they're actually more flexible than you might expect.
The syntax for control structures in Go is a bit unusual, with no parentheses and all bodies must be brace-delimited. This makes it easy to use a single err value in a long if-else chain, which you'll see often in Go code.
One of the unique features of Go's control flow is the use of implicit blocks, which can be a bit tricky to understand at first. Here's a quick rundown of the different types of implicit blocks:
- The universe block encompasses all Go source text.
- Each package has a package block containing all Go source text for that package.
- Each file has a file block containing all Go source text in that file.
- Each "if", "for", and "switch" statement is considered to be in its own implicit block.
- Each clause in a "switch" or "select" statement acts as an implicit block.
Overall, understanding control flow in Go takes a bit of practice, but it's a powerful tool for writing efficient and effective code.
Blocks
Blocks in Go are a fundamental concept in control flow, and they're more than just a way to group code together. A block is a possibly empty sequence of declarations and statements within matching brace brackets.
There are several types of blocks in Go, including explicit blocks in the source code, and implicit blocks that are created by the language itself. Implicit blocks are created for the universe, each package, each file, and for certain statements like if, for, and switch.
The universe block encompasses all Go source text, while each package has a package block containing all Go source text for that package. Each file also has a file block containing all Go source text in that file.
Blocks nest and influence scoping, which means that variables declared inside a block are only accessible within that block. This helps to avoid naming conflicts and make the code more organized.
Here are the different types of implicit blocks in Go:
- The universe block
- Package block
- File block
- if, for, and switch statement blocks
- Clauses in a switch or select statement blocks
By understanding blocks in Go, you can write more efficient and organized code that's easier to read and maintain.
Control Structures
Control structures in Go are a bit different from what you might be used to in other languages. There's no do or while loop, only a slightly generalized for statement.
Go's for statement can have an optional initialization statement, just like the if and switch statements. This can be useful for declaring variables before the loop starts.
One thing to note is that the scope of function parameters and return values in Go is the same as the function body, even though they appear outside the braces that enclose the body.
The switch statement in Go is more general than in C, and the expressions don't need to be constants or integers. The cases are evaluated top to bottom until a match is found, and if the switch has no expression, it switches on true.
Here are some key differences between Go's switch statement and C's:
Go also has a type switch, which compares types rather than values. It's similar to an expression switch, but uses the keyword type inside the parentheses.
The type switch guard can include a short variable declaration, which is declared at the end of the type switch case in the implicit block of each clause. This can be useful for declaring a variable with a type that's different from the type of the expression in the type switch guard.
In a type switch, the variable declared in the type switch guard has the type of the expression in the type switch guard, unless the case lists exactly one type, in which case the variable has that type.
Additional reading: Switch Statement Golang
Recover
Recover is a powerful tool that allows you to regain control of a goroutine that's panicking. It stops the unwinding of the stack and returns the argument passed to panic.
To use recover, you need to call it inside a deferred function, as it's only useful there. This is because the only code that runs while unwinding is inside deferred functions.
A call to recover stops the unwinding and returns the argument passed to panic, but it always returns nil unless called directly from a deferred function. This means that deferred code can call library routines that themselves use panic and recover without failing.
Recover can be used to shut down a failing goroutine inside a server without killing the other executing goroutines. For example, if do(work) panics, the result will be logged and the goroutine will exit cleanly without disturbing the others.
In the context of error handling, recover can be used to simplify error reporting by re-panicking with a local error type. This is useful when working with libraries that report errors by panicking, such as the regexp package. If doParse panics, the recovery block will set the return value to nil and then check if the problem was a parse error by asserting that it has the local type Error.
For another approach, see: Golang Create Error
Appending to and Copying Slices
Appending to and copying slices is a fundamental concept in Go programming. You can use the built-in functions append and copy to perform these operations.
The append function appends zero or more values to a slice and returns the resulting slice. It re-uses the underlying array if there's enough capacity, otherwise it allocates a new array.
The copy function copies elements from a source slice to a destination slice and returns the number of elements copied. The number of elements copied is the minimum of the source and destination slice lengths.
You can use the append function to add elements to a slice, even if the slice is initialized with a string. The string will be converted to a byte slice.
The copy function doesn't copy all elements from the source slice, only up to the length of the destination slice.
Here's a summary of the append and copy functions:
Note that the append function modifies the underlying array if it needs to be reallocated, whereas the copy function only copies elements up to the length of the destination slice.
Close
Closing a channel is a crucial operation that signals no more values will be sent on it. This is achieved through the built-in function close(ch), which records that no more values will be sent on the channel.
Sending to or closing a closed channel causes a run-time panic. Closing the nil channel also causes a run-time panic.
After calling close, receive operations will return the zero value for the channel's type without blocking. This means you can be sure that no more values will be sent on the channel.
The multi-valued receive operation returns a received value along with an indication of whether the channel is closed. This is useful for handling the channel's status in a more nuanced way.
If the type of the argument to close is a type parameter, all types in its type set must be channels with the same element type. This ensures consistency in the channel's usage.
It's an error if any of those channels is a receive-only channel. This means you can't close a receive-only channel using the close function.
Broaden your view: How to Run Golang File
Delete Map Elements
To delete a map element, you can use the built-in function delete, which removes the element with a given key from a map.
The value of the key you want to delete must be assignable to the key type of the map, ensuring a smooth deletion process.
If the map is nil or the element you're trying to delete doesn't exist, the delete function is essentially a no-op, meaning it won't do anything.
In other words, it's essential to double-check that the map exists and the key you're trying to delete is valid before attempting to remove it.
Operators
Operators are the building blocks of expressions, and understanding how they work is crucial for writing effective code.
Operators combine operands into expressions, and for most binary operators, the operand types must be identical unless the operation involves shifts or untyped constants.
In shift expressions, the right operand must have integer type or be an untyped constant representable by a value of type uint.
If one operand is an untyped constant and the other operand is not, the constant is implicitly converted to the type of the other operand.
Here are some key rules to keep in mind:
The order of evaluation for expressions is also important to understand. In general, all function calls, method calls, receive operations, and binary logical operations are evaluated in lexical left-to-right order.
This means that if you have a statement like `f(), h() (if z evaluates to false), i(), j(), <-c, g(), and k()`, the function calls and communication will happen in the order listed, but the order of other events compared to the evaluation and indexing of variables is not specified.
Send Statement
The send statement is a fundamental part of control flow in programming. It's denoted by the lexical token "<-".
In a send statement, the value is sent through a channel, but it doesn't return any value, so there's no need to make an expression out of it. This makes it a simple and straightforward way to send data between goroutines.
To use a send statement, you specify the channel and the value to be sent. The channel direction must permit send operations, and the type of the send operation is the element type of the channel. For example, in the send statement <-c, the channel c is the operand, and the value to be sent is not specified.
If you're working with channels, it's essential to understand how send statements work, especially when dealing with nil channels or closed channels. In the case of a nil channel, the send statement will block forever, while a closed channel will always allow the send operation to proceed immediately.
Additional reading: Golang Chan
Order of Evaluation
In Go, the order of evaluation is determined by lexical left-to-right order, unless otherwise specified.
Function calls, method calls, receive operations, and binary logical operations are evaluated in this order, as seen in the example assignment: f(), h() (if z evaluates to false), i(), j(), <-c, g(), and k(). However, the order of events compared to the evaluation and indexing of x and the evaluation of y and z is not specified, except as required lexically.
At package level, initialization dependencies override the left-to-right rule for individual initialization expressions, but not for operands within each expression. This means that function calls happen in the order u(), sqr(), v(), f(), v(), and g().
Explicit parentheses can affect the evaluation by overriding the default associativity, as seen in the expression x + (y + z), where the addition y + z is performed before adding x.
Check this out: Specs for Iphone X
Labeled
Labeled statements can be the target of a goto, break, or continue statement. This means you can use a labeled statement to jump to a specific point in your code using a goto statement.
A labeled statement can be used to indicate a specific point in the code that you want to jump to. This can be useful for creating complex control flow scenarios.
Arguments of type parameter type are not permitted in labeled statements. This means you can't use a type parameter as a label, which can help prevent errors in your code.
Expand your knowledge: Golang Comments
Assertions
Assertions are a way to ensure the type of a value is what we expect it to be. They can be used to check if a value is not nil and of a specific type.
A type assertion is made using the notation x.(T), where x is the value and T is the expected type. This asserts that the dynamic type of x is identical to the type T.
If the type assertion holds, the value of the expression is the value stored in x and its type is T. If the type assertion is false, a run-time panic occurs.
A type assertion can be used in an assignment statement or initialization, in which case it yields an additional untyped boolean value. This value is true if the assertion holds, and false otherwise.
Type assertions can be used to extract a value from an interface, but they can also cause a run-time panic if the value is not of the expected type. To avoid this, we can use the "comma, ok" idiom to test whether the value is of the expected type.
Program Execution
Program execution is a key aspect of control flow in programming. The main function does not wait for other goroutines to complete, unlike some other programming languages.
In Go, this means that the main function will terminate as soon as it finishes executing its code, regardless of the status of other goroutines. This can sometimes lead to unexpected behavior if not handled properly.
Discover more: Golang Test Main
Empty Statement
In Golang, the concept of an empty statement is quite different from other languages. There is no prefix version, meaning you can't use "—" or "++" before an operand.
In Golang, the lack of a prefix version for the empty statement is notable. This is a deliberate design choice that sets it apart from other languages.
The empty statement in Golang is essentially a no-op, meaning it doesn't perform any action. This is in contrast to other languages where the empty statement might be used to increment or decrement a variable.
A different take: Golang Version Manager
Functions and Methods
A function declaration binds an identifier to a function, and if the function's signature declares result parameters, the function body's statement list must end in a terminating statement.
In Go, a method is a function with a receiver, which is specified via an extra parameter section preceding the method name. The receiver type must be a defined type T or a pointer to a defined type T, and it must be defined in the same package as the method.
The type of a method is the type of a function with the receiver as first argument, and for instance, the method Scale has type `func(*Point)`. This means that even if the receiver is nil, the method can still be called.
Here's a summary of the types of receiver types:
- Defined type T: The method set of a defined type T consists of all methods declared with receiver type T.
- Pointer to a defined type T: The method set of a pointer to a defined type T is the set of all methods declared with receiver *T or T.
- Interface type: The method set of an interface type is the intersection of the method sets of each type in the interface's type set.
Function
A function declaration binds an identifier, the function name, to a function. This identifier is the name that will be used to call the function.
A function declaration may omit the body, providing the signature for a function implemented outside Go, such as an assembly routine. This is useful when you need to call a function that is implemented in a library or framework.
If a function's signature declares result parameters, the function body's statement list must end in a terminating statement. This ensures that the function returns a value when called.
A function declaration without type parameters may omit the body. This allows you to declare a function without providing its implementation, which can be useful when working with external libraries or frameworks.
A function declaration specifies type parameters, the function name denotes a generic function. A generic function must be instantiated before it can be called or used as a value.
The type of a method is the type of a function with the receiver as first argument. For instance, the method Scale has type T.Scale, where T is the type of the receiver.
A method is a function with a receiver, and its type must be a defined type T or a pointer to a defined type T. This means that a method can only be bound to a type that is defined in the same package as the method.
A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type. The receiver is specified via an extra parameter section preceding the method name.
A function value derived from a method is called with function call syntax, with the receiver provided as the first argument to the call. For example, given f := T.Mv, f is invoked as f(t, 7) not t.f(7).
For
Functions are reusable blocks of code that can be called multiple times in a program. They can perform a specific task or a set of related tasks.
A function can take arguments, which are values passed to it when it's called. This allows functions to be flexible and work with different types of data.
Functions can also return values, which can be used by the calling code. This enables functions to produce output and interact with other parts of the program.
Consider reading: Golang Source Code

Methods, on the other hand, are functions that belong to a class or object. They operate on the data stored in the class or object, and are used to perform specific actions or operations.
Methods can be called using the dot notation, with the class or object name followed by the method name.
Consider reading: Golang Class
Comparison
Comparison is a key aspect of functions and methods in programming. Pointers to distinct zero-size variables may or may not be equal.
Struct values can be compared if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal, just like how I compare two structs with identical fields.
Slice, map, and function values are not comparable, which can be a limitation when working with these data types. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil.
Here's an interesting read: Golang Copy Struct
Error Handling
Error handling is a crucial aspect of Go programming, and it's essential to understand how to handle errors effectively.
The predeclared type error is used to represent an error condition, with the nil value indicating no error. This type is a simple built-in interface that allows library routines to return a detailed error description alongside the normal return value.
Go's multivalue return makes it easy to return a detailed error description, and it's good style to use this feature to provide detailed error information. For example, the os.Open function returns an error value that describes what went wrong, making it possible to see the error and provide context.
The error strings should identify their origin, such as by having a prefix naming the operation or package that generated the error. This can be seen in the image package, where the string representation for a decoding error due to an unknown format is "image: unknown format".
If the error is unrecoverable, the program can use the built-in function panic to create a run-time error that will stop the program. However, it's recommended to avoid panicking in library functions and instead let things continue to run.
Discover more: Golang Format Time
Errors
In Go, errors are typically represented using the predeclared type error, which is defined as an empty interface. This type is the conventional interface for representing an error condition, with the nil value representing no error.
To provide detailed error information, library routines should return an error value alongside the normal return value. This is good style and makes it easy for the caller to see what went wrong. For example, the os.Open function returns an error value that describes what went wrong when the file cannot be opened.
The error type is an interface, which means library writers can implement it with a richer model under the covers. This makes it possible not only to see the error but also to provide some context. For instance, the os.PathError type includes an internal Err field that can be examined for recoverable failures.
To report an error to a caller, it's common to return an error as an extra return value. The canonical Read method is a well-known instance of this pattern, returning a byte count and an error. However, if the error is unrecoverable, it's better to let the program continue running rather than taking it down entirely.
Here are some common error types in Go:
- error: the conventional interface for representing an error condition
- os.PathError: includes an internal Err field for recoverable failures
- runtime.Error: an implementation-defined interface type representing a run-time error condition
It's also worth noting that the panic function can be used to create a run-time error that will stop the program. However, this should be used sparingly and only within a package, as it's generally better to let the program continue running rather than taking it down entirely.
Checks
Checks are an essential part of error handling, and they can be performed both at compile time and run time.
Static checks happen when the compiler verifies that a type implements an interface. For example, passing an *os.File to a function expecting an io.Reader will not compile unless *os.File implements the io.Reader interface.
Some interface checks are performed at run time, such as in the encoding/json package, where the JSON encoder checks if a value implements the Marshaler interface by using a type assertion.
If you only need to ask if a type implements an interface without using it, you can use the blank identifier to ignore the type-asserted value. This is useful for error checks.
If this caught your attention, see: Golang Io
In some cases, you need to guarantee that a type satisfies an interface, such as when implementing a custom JSON representation. You can do this by using a global declaration with the blank identifier. This will check the interface property at compile time.
Don't use this technique for every type that satisfies an interface, though - it's only necessary when there are no static conversions already present in the code.
Package and Import
In Go, a package clause defines the package to which a source file belongs. Each source file must have a package clause that specifies the package name, which must not be the blank identifier.
A package clause is used to group related files together, and all files sharing the same package name form the implementation of a package. This means that all source files for a package must inhabit the same directory.
To import a package, you use an import declaration, which states that the source file containing the declaration depends on the functionality of the imported package. This allows access to the exported identifiers of the package.
Suggestion: Create a Package in Golang
Here's a table illustrating how to access the exported identifier Sin in files that import the package after various types of import declarations:
To import a package solely for its side effects, use the blank identifier as the explicit package name. This makes it clear that the package is being imported for its side effects, as there is no other possible use of the package.
Import
An import declaration states that the source file containing the declaration depends on functionality of the imported package. This enables access to exported identifiers of that package.
The import names an identifier (PackageName) to be used for access and an ImportPath that specifies the package to be imported. The PackageName is used in qualified identifiers to access exported identifiers of the package within the importing source file.
If the PackageName is omitted, it defaults to the identifier specified in the package clause of the imported package. This can be useful when importing a package solely for its side effects.
Implementation restriction: A compiler may restrict ImportPaths to non-empty strings using only characters belonging to Unicode's Graphic characters without spaces. This means that certain characters like !, @, and $ may not be used in the ImportPath.
To import a package solely for its side effects, use the blank identifier as explicit package name. This makes clear that the package is being imported for its side effects.
Here's a table illustrating how to access the exported identifiers of a package after importing it with different types of import declarations:
An alias declaration may be used to declare an alias name for a type. This can be useful when importing a package and wanting to use a different name for a type.
An identifier may be exported to permit access to it from another package. An identifier is exported if its first character is a Unicode uppercase letter and it is declared in the package block or is a field name or method name.
All other identifiers are not exported. This means that only certain identifiers can be accessed from another package.
Alias
In Go, an alias declaration is a way to bind an identifier to a given type, which serves as an alias for the type within its scope.
This means that when you use an alias, it's essentially a shorthand way of referring to the original type.
In Go 1.9, alias declarations were introduced, and they've been a game-changer for many developers.
An alias declaration can be used to simplify complex type names or to make your code more readable.
The given type in an alias declaration cannot be a type parameter, so you'll need to choose a different type if you want to use type parameters.
If the alias declaration specifies type parameters, the type name denotes a generic alias, which must be instantiated when it's used, starting from Go 1.24.
Package Unsafe
Packages can be installed from untrusted sources, which can pose a security risk to your project.
This can happen if you install packages using a package manager that doesn't verify the package's integrity.
Installing packages from a CDN can also be a problem if the CDN is compromised.
The best way to avoid this is to use a package manager that verifies the package's integrity, such as npm.
Some package managers may also have a feature to specify a specific URL for the package, which can be used to install packages from trusted sources.
You can also check the package's dependencies to see if any of them are vulnerable.
Embedding
In Go, you can embed one interface inside another, which is a powerful feature that allows for more flexible and reusable code.
Embedding an interface means using a type name as an interface element, and it's called embedding interface E in T. The type set of T is the intersection of the type sets defined by T's explicitly declared methods and the type sets of T's embedded interfaces.
A union cannot contain the predeclared identifier comparable or interfaces that specify methods, or embed comparable or interfaces that specify methods.
This means you can embed methods with the same names from different interfaces, and it's not an error if you do so.
Methods with the same names must have identical signatures when embedding interfaces.
Curious to learn more? Check out: T Golang
Concurrency
Concurrency is a fundamental aspect of Go programming, and it's what makes Go so efficient and scalable. Goroutines are the building blocks of concurrency in Go.
A goroutine is a function executing concurrently with other goroutines in the same address space, costing little more than the allocation of stack space. Goroutines are multiplexed onto multiple OS threads so if one should block, others continue to run.
Prefixing a function or method call with the go keyword runs the call in a new goroutine. When the call completes, the goroutine exits silently.
Function literals can be handy in goroutine invocations because they are closures that ensure the variables referred to by the function survive as long as they are active. This is especially useful when working with channels.
Channels are a key component of concurrency in Go, and they can be used to communicate between goroutines. Channels are allocated with the make function, and the resulting value acts as a reference to an underlying data structure.
Unbuffered channels combine communication with synchronization, guaranteeing that two calculations are in a known state. Buffered channels, on the other hand, can be used to limit throughput by setting a buffer size.
A common use of channels is to implement safe, parallel demultiplexing. This involves passing a channel of channels between goroutines, allowing them to communicate with each other in a controlled manner.
Featured Images: pexels.com


