This guide shows each change from the Go 17th birthday post as code. Where a change replaces an old pattern, you see the code before and after.
Releases: Go 1.26 (February), Go 1.27 (August)Source:go.dev/blog/17yearsWritten by: Claude Opus 5.5
The year in one line. Two feature releases, one API launch, and one urgent security release.
How to read this guide
Code pairsThe left block shows the old pattern. The right block shows the new pattern. The label gives the release.
TagsA tag gives the release of the change. The tag No code change shows that an upgrade is sufficient.
ExplanationsA box below each example tells you what the code does and describes its data structures. Go experience is not necessary.
Run itOpen Complete program and output below an example. You get a full file that you can copy and run, and the output that was recorded.
Basic terms
The explanations use these terms. Read them first if you are new to programming.
PackageA group of Go files with one purpose. import lets your file use a package. fmt prints text. time works with time.
VariableA name for a value in memory. x := 3 declares the variable x and gives it the value 3.
TypeThe kind of a value. int is a whole number. string is text. bool is true or false. byte is one unit of raw data.
FunctionA named block of code. It accepts inputs and returns results. The program starts in func main().
MethodA function that belongs to a type. You call it with a dot: value.Method().
StructA group of named fields that make one value, for example a user with an ID and a name.
PointerThe address of a value in memory. *int is a pointer to an int. &x is the address of x. nil means no value.
SliceAn ordered list that can grow. []int is a slice of whole numbers. append adds an item.
MapA table that finds a value from a key. map[string]int finds a whole number from text.
InterfaceA list of methods. Each type that has those methods can be used where the interface is necessary.
GenericCode with a placeholder for a type, written in square brackets: [T any]. One function then works for many types.
ErrorA value that tells you that an operation failed. A function returns it as its last result. nil means no error.
GoroutineA function that runs at the same time as other code. The word go starts it.
ChannelA pipe between goroutines. One goroutine sends a value and a different goroutine receives it.
CommentText after //. It is for the reader. The compiler ignores it.
Prepare a work area
Install Go 1.27 or later. Make sure with go version.
Make a module: mkdir go17 && cd go17 && go mod init go17
Copy an example into main.go. Add package main and the imports if the example is a fragment.
Start the program: go run .
NOTE The examples were compiled and run with Go 1.26.6 and Go 1.27.4 on linux/amd64. Three items need the network and were not tested: the github.com/google/uuid example, the gopls and govulncheck commands, and go doc with a version. The performance values were not measured. The complete programs and their outputs were recorded with Go 1.27.4.
1
Language
Five changes. Each change removes a workaround. Old code continues to compile.
1.1
new with a value
Go 1.26
The built-in function new now accepts an expression. The expression gives the initial value of the variable.
Use this change for optional fields that are pointers. JSON and protocol buffer structures frequently have such fields.
Before Go 1.26
type Patch struct {
Name *string `json:"name,omitempty"`
Retries *int `json:"retries,omitempty"`
}
// A helper function was necessary.func ptr[T any](v T) *T { return &v }
func main() {
p := Patch{
Name: ptr("payments"),
Retries: ptr(3),
}
_ = p
}
Go 1.26
type Patch struct {
Name *string `json:"name,omitempty"`
Retries *int `json:"retries,omitempty"`
}
func main() {
p := Patch{
Name: new("payments"), // *string
Retries: new(3), // *int
}
// An expression is also permitted.
deadline := new(time.Now().Add(time.Hour)) // *time.Time
_, _ = p, deadline
}
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"fmt""time"
)
type Patch struct {
Name *string `json:"name,omitempty"`
Retries *int `json:"retries,omitempty"`
}
func main() {
p := Patch{
Name: new("payments"), // *string
Retries: new(3), // *int
}
// An expression is also permitted.
deadline := new(time.Now().Add(time.Hour)) // *time.Time// The star gets the value that the pointer points to.
fmt.Println(*p.Name, *p.Retries)
fmt.Println(deadline.After(time.Now()))
}
Terminal · recorded with Go 1.27.4
$ go run .
payments 3
true
What the code does
The two programs make a Patch value. A Patch describes a change to a record. Each field is optional: you fill only the fields that you want to change.
The old program needs a small helper function, ptr. It accepts a value and gives back the address of a copy of that value. The new program uses the built-in function new for the same work. new("payments") makes a new text variable that contains payments and gives you its address.
The line with deadline makes a pointer to a time that is one hour from now.
Data structures
Patch is a struct: a group of named fields. It has the fields Name and Retries.
*string and *int are pointer types. A pointer holds the address of a value. A pointer can also be nil, which means that there is no value. A plain int cannot show the difference between 0 and "not given". A pointer can.
The text in backquotes after each field is a struct tag. It tells the JSON package which name to use for the field. omitempty tells it to leave out the field when the field is empty.
ptr[T any] is a generic function. T is a placeholder for a type. Thus one function works for text, numbers and all other types.
NOTEnew(T) with a type continues to work. new(3) makes a pointer to an int variable with the value 3.
1.2
Type constraints that refer to themselves
Go 1.26
A generic type can now refer to itself in its type parameter list.
You can write a constraint that says: the method accepts the same type and returns the same type.
Before Go 1.26
// Compile error before Go 1.26:// Adder refers to itself in its type parameter list.//// type Adder[A Adder[A]] interface { Add(A) A }// Workaround: write the constraint again// in each function.func Sum[A interface{ Add(A) A }](xs ...A) A {
var total A
for _, x := range xs {
total = total.Add(x)
}
return total
}
Go 1.26
type Adder[A Adder[A]] interface {
Add(A) A
}
type Cents int64
func (c Cents) Add(d Cents) Cents { return c + d }
func Sum[A Adder[A]](xs ...A) A {
var total A
for _, x := range xs {
total = total.Add(x)
}
return total
}
func main() {
fmt.Println(Sum(Cents(250), Cents(199))) // 449
}
Complete program and output
main.go · needs Go 1.26 or later
package main
import"fmt"type Adder[A Adder[A]] interface {
Add(A) A
}
type Cents int64
func (c Cents) Add(d Cents) Cents { return c + d }
func Sum[A Adder[A]](xs ...A) A {
var total A
for _, x := range xs {
total = total.Add(x)
}
return total
}
func main() {
fmt.Println(Sum(Cents(250), Cents(199)))
}
Terminal · recorded with Go 1.27.4
$ go run .
449
What the code does
Sum adds a list of values and returns the total. It works for each type that has an Add method. The loop starts with an empty total. Then it adds the values one at a time.
The program adds 250 cents and 199 cents and prints 449.
In the old code, the rule "the type has an Add method" is in the declaration of Sum. You write it again in each function that needs it. In the new code the rule has a name, Adder, and each function can use that name.
Data structures
Cents is a new type that holds an int64, a whole number of 64 bits. Money in cents has no fractions, thus the arithmetic is exact.
func (c Cents) Add(d Cents) Cents is a method: a function that belongs to the type Cents. You call it with a dot: total.Add(x).
Adder[A] is an interface: a list of methods that a type must have. This one says: type A has a method Add that accepts an A and returns an A. The interface uses its own name in its declaration. That was not permitted before Go 1.26.
xs ...A lets the caller give any number of values. In the function, xs is a slice: an ordered list.
var total A makes a variable with the zero value of its type. For a number type, the zero value is 0.
1.3
Generic methods
Go 1.27
A method declaration can now have its own type parameters. This limit was in the language from Go 1.18.
Before, a generic operation on a type was a package-level function. Now the operation can be a method of the type.
A generic method keeps the operation in the namespace of the type. The call reads in the sequence of the data flow.
Before Go 1.27
type Stream[T any] struct{ items []T }
func Of[T any](items ...T) Stream[T] { return Stream[T]{items} }
func (s Stream[T]) Filter(keep func(T) bool) Stream[T] {
var out []T
for _, v := range s.items {
if keep(v) {
out = append(out, v)
}
}
return Stream[T]{out}
}
// Map changes T to U. A method could not declare U.func Map[T, U any](s Stream[T], f func(T) U) Stream[U] {
out := make([]U, 0, len(s.items))
for _, v := range s.items {
out = append(out, f(v))
}
return Stream[U]{out}
}
func main() {
isEven := func(n int) bool { return n%2 == 0 }
s := Map(Of(1, 2, 3, 4).Filter(isEven), strconv.Itoa)
fmt.Println(s.items) // [2 4]
}
Go 1.27
type Stream[T any] struct{ items []T }
func Of[T any](items ...T) Stream[T] { return Stream[T]{items} }
func (s Stream[T]) Filter(keep func(T) bool) Stream[T] {
var out []T
for _, v := range s.items {
if keep(v) {
out = append(out, v)
}
}
return Stream[T]{out}
}
// The method declares its own type parameter U.func (s Stream[T]) Map[U any](f func(T) U) Stream[U] {
out := make([]U, 0, len(s.items))
for _, v := range s.items {
out = append(out, f(v))
}
return Stream[U]{out}
}
func main() {
isEven := func(n int) bool { return n%2 == 0 }
s := Of(1, 2, 3, 4).Filter(isEven).Map(strconv.Itoa)
fmt.Println(s.items) // [2 4]
}
Complete program and output
main.go · needs Go 1.27 or later
package main
import (
"fmt""strconv"
)
type Stream[T any] struct{ items []T }
func Of[T any](items ...T) Stream[T] { return Stream[T]{items} }
func (s Stream[T]) Filter(keep func(T) bool) Stream[T] {
var out []T
for _, v := range s.items {
if keep(v) {
out = append(out, v)
}
}
return Stream[T]{out}
}
// The method declares its own type parameter U.func (s Stream[T]) Map[U any](f func(T) U) Stream[U] {
out := make([]U, 0, len(s.items))
for _, v := range s.items {
out = append(out, f(v))
}
return Stream[U]{out}
}
func main() {
isEven := func(n int) bool { return n%2 == 0 }
s := Of(1, 2, 3, 4).Filter(isEven).Map(strconv.Itoa)
fmt.Println(s.items)
}
Terminal · recorded with Go 1.27.4
$ go run .
[2 4]
What the code does
The program makes a stream that holds the numbers 1, 2, 3 and 4. It keeps the even numbers (2 and 4). Then it changes each number to text. It prints [2 4].
Filter looks at each item and keeps it only if the function keep returns true. Map calls the function f on each item and collects the results.
Map changes the item type, here from number to text. Thus it needs a second type placeholder, U. In the old code a method could not declare U, so Map was a separate function and the call reads from the inside out. In the new code Map is a method and the steps read from left to right.
Data structures
Stream[T] is a generic struct. It has one field, items, which is a slice of T. Stream[int] holds whole numbers. Stream[string] holds text.
func(T) bool is a function type. In Go you can give a function to a different function as an argument. isEven and strconv.Itoa are used in this way.
strconv.Itoa changes a whole number to text: 2 becomes "2".
make([]U, 0, len(s.items)) makes an empty slice with space for all the results. append adds one item to the end of a slice.
n%2 == 0 is true when the remainder of n divided by 2 is zero, thus when n is even.
The standard library uses the feature. math/rand/v2 has a new generic method Rand.N.
Before Go 1.27
r := rand.New(rand.NewPCG(1, 2))
// Convert to int64, then convert back.
wait := time.Duration(r.Int64N(int64(5 * time.Second)))
Go 1.27
r := rand.New(rand.NewPCG(1, 2))
// N accepts each integer type.
wait := r.N(5 * time.Second) // time.Duration
Complete program and output
main.go · needs Go 1.27 or later
package main
import (
"fmt""math/rand/v2""time"
)
func main() {
r := rand.New(rand.NewPCG(1, 2))
// N accepts each integer type.
wait := r.N(5 * time.Second) // time.Duration
fmt.Println(wait)
}
Terminal · recorded with Go 1.27.4
$ go run .
3.846866346s
The seed is fixed, thus each run prints the same value.
What the code does
The code selects a random wait time that is less than 5 seconds. Programs do this, for example, before they try a failed request again.
The old method Int64N accepts only the type int64. Thus you change the duration to int64 and then change the result back. The new method N accepts each whole-number type and returns the same type.
Data structures
r is a random number generator. rand.NewPCG(1, 2) is its source. The numbers 1 and 2 are the seed. The same seed always gives the same sequence of numbers, which is useful in tests.
time.Duration is a length of time. Go stores it as a whole number of nanoseconds. 5 * time.Second is five seconds.
:= declares a variable and gives it a value in one step.
CAUTION An interface method cannot have type parameters. A generic method cannot implement an interface method.
1.4
More type inference for generic functions
Go 1.27
The compiler now infers type arguments in each context where you assign a generic function to a matching function type.
This includes conversions and composite literals.
Before Go 1.27
func first[T any](s []T) T { return s[0] }
func last[T any](s []T) T { return s[len(s)-1] }
// The type arguments were necessary.
ops := []func([]int) int{first[int], last[int]}
Go 1.27
func first[T any](s []T) T { return s[0] }
func last[T any](s []T) T { return s[len(s)-1] }
// The element type gives T = int.
ops := []func([]int) int{first, last}
Complete program and output
main.go · needs Go 1.27 or later
package main
import"fmt"func first[T any](s []T) T { return s[0] }
func last[T any](s []T) T { return s[len(s)-1] }
func main() {
// The element type gives T = int.
ops := []func([]int) int{first, last}
nums := []int{10, 20, 30}
for _, op := range ops {
fmt.Println(op(nums))
}
}
Terminal · recorded with Go 1.27.4
$ go run .
10
30
What the code does
first returns the first item of a list. last returns the last item. They are generic: they work for a list of any type.
The last line puts the two functions into a list with the name ops. In the old code you had to write first[int] to say that the type is int. In the new code the compiler finds the type from the type of the list.
Data structures
[]func([]int) int is a slice of functions. Each function in it accepts a slice of whole numbers and returns one whole number. A function is a value in Go: you can keep it in a variable or in a list.
s[0] is the first item of the slice s. Positions start at 0. len(s) is the number of items, thus s[len(s)-1] is the last item.
1.5
Struct literal keys for embedded fields
Go 1.27
A key in a struct literal can now be a field selector of the struct type. Before, only a top-level field name was permitted.
You can set a promoted field directly. You do not write the embedded type again.
Before Go 1.27
type Base struct {
ID int
Created time.Time
}
type User struct {
Base
Name string
}
u := User{
Base: Base{ID: 7},
Name: "Mittens",
}
Go 1.27
type Base struct {
ID int
Created time.Time
}
type User struct {
Base
Name string
}
u := User{
ID: 7, // promoted from Base
Name: "Mittens",
}
Complete program and output
main.go · needs Go 1.27 or later
package main
import (
"fmt""time"
)
type Base struct {
ID int
Created time.Time
}
type User struct {
Base
Name string
}
func main() {
u := User{
ID: 7, // promoted from Base
Name: "Mittens",
}
fmt.Println(u.ID, u.Name)
}
Terminal · recorded with Go 1.27.4
$ go run .
7 Mittens
What the code does
The code makes a User with the ID 7 and the name Mittens.
In the old code you write the inner struct Base in full to set ID. In the new code you set ID directly.
Data structures
Base is a struct with two fields: ID (a whole number) and Created (a moment in time, of type time.Time).
User is a struct that embeds Base. To embed, you write the type with no field name. Then User gets the fields of Base. You can write u.ID. Such a field is called a promoted field.
The code does not set Created. It keeps its zero value.
User{...} is a composite literal: it makes a struct value and fills the fields that you name.
NOTE The new embedlit modernizer of go fix is related to this change. Refer to section 5.1.
2
Standard library
A new JSON engine, a leak profiler, faster HTTP/1 clients, and three new APIs.
2.1
encoding/json/v2 and jsontext
Go 1.276 years of work
Go 1.27 has two new packages. encoding/json/v2 changes Go values to JSON and back. encoding/json/jsontext reads and writes JSON tokens without reflection.
The old package encoding/json now uses the v2 engine. Your code gets faster unmarshal operations and you do not change it. The blog post gives a maximum of 10 times.
One engine, two APIs. Version 1 is a thin layer on version 2. The two versions can be in the same program.
Stricter defaults
Version 1 accepts input that can hide errors or attacks. Version 2 rejects this input.
Input or value
Version 1
Version 2 default
Option for the v1 behavior
Duplicate name: {"role":"viewer","role":"admin"}
Accepts. The last value wins.
Error
jsontext.AllowDuplicateNames(true)
Different case: {"ROLE":"admin"} for the tag json:"role"
package main
import (
"encoding/json""fmt"
)
type Account struct {
ID string `json:"id"`
Role string `json:"role"`
Tags []string `json:"tags"`
}
func main() {
in := []byte(`{"id":"a1","role":"viewer","ROLE":"admin"}`)
var a Account
err := json.Unmarshal(in, &a)
fmt.Println(a.Role, err) // admin <nil>
out, _ := json.Marshal(Account{ID: "a1"})
fmt.Println(string(out))
// {"id":"a1","role":"","tags":null}
}
Version 2 behavior
package main
import (
"encoding/json/v2""fmt"
)
type Account struct {
ID string `json:"id"`
Role string `json:"role"`
Tags []string `json:"tags"`
}
func main() {
in := []byte(`{"id":"a1","role":"viewer","ROLE":"admin"}`)
var a Account
err := json.Unmarshal(in, &a)
fmt.Println(a.Role, err) // viewer <nil>: "ROLE" does not match
out, _ := json.Marshal(Account{ID: "a1"})
fmt.Println(string(out))
// {"id":"a1","role":"","tags":[]}
}
Output of the program
Version 1 · recorded with Go 1.27.4
$ go run .
admin <nil>
{"id":"a1","role":"","tags":null}
Version 2 · recorded with Go 1.27.4
$ go run .
viewer <nil>
{"id":"a1","role":"","tags":[]}
The examples above are complete programs. Copy one into main.go and do go run ..
What the code does
JSON is a text format for data. Programs use it to send data to other programs. Each program does two steps. First it reads JSON text into an Account (this is "unmarshal"). Then it writes an Account as JSON text (this is "marshal").
The input has two members with almost the same name: "role":"viewer" and "ROLE":"admin". Version 1 ignores the difference between capital and small letters. The second member replaces the first, and the role becomes admin. An attacker can use this to hide a value. Version 2 accepts only the exact name, and the role stays viewer.
In the output, Tags has no items. Version 1 writes null. Version 2 writes an empty list, [].
Data structures
Account is a struct with three fields. The struct tags give the JSON name of each field.
[]byte is a slice of bytes: raw data. The JSON functions read bytes and write bytes. string(out) changes bytes to text for the print.
&a is the address of the variable a. Unmarshal needs the address to put the data into a.
Tags []string is a slice of text values. It is nil when nothing was put into it.
err is an error value. nil means that there was no error. out, _ := puts the first result in out and discards the second.
Options at the call site
Each v2 function accepts options. The caller controls the behavior for one call. In version 1 you made a Decoder or a wrapper type.
Version 1
// Reject unknown fields: a Decoder was necessary.
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
err := dec.Decode(&cfg)
// Unix time for time.Time: a wrapper type// with a MarshalJSON method was necessary.type unixTime time.Time
func (t unixTime) MarshalJSON() ([]byte, error) {
return strconv.AppendInt(nil, time.Time(t).Unix(), 10), nil
}
Version 2
// Reject unknown members with one option.
err := json.UnmarshalRead(r, &cfg,
json.RejectUnknownMembers(true))
// The caller gives a marshal function for time.Time.// The struct types do not change.
unix := json.MarshalFunc(func(t time.Time) ([]byte, error) {
return strconv.AppendInt(nil, t.Unix(), 10), nil
})
out, err := json.Marshal(event, json.WithMarshalers(unix))
Complete program and output
main.go · needs Go 1.27 or later
package main
import (
"encoding/json/v2""fmt""strconv""strings""time"
)
type Config struct {
Name string `json:"name"`
}
type Event struct {
Title string `json:"title"`
At time.Time `json:"at"`
}
func main() {
// The input has a member that Config does not have.
r := strings.NewReader(`{"name":"db","nmae":"typing error"}`)
// Reject unknown members with one option.var cfg Config
err := json.UnmarshalRead(r, &cfg, json.RejectUnknownMembers(true))
fmt.Println("error:", err)
// The caller gives a marshal function for time.Time.// The struct types do not change.
unix := json.MarshalFunc(func(t time.Time) ([]byte, error) {
return strconv.AppendInt(nil, t.Unix(), 10), nil
})
event := Event{Title: "deploy", At: time.Unix(1700000000, 0)}
out, err := json.Marshal(event, json.WithMarshalers(unix))
fmt.Println(string(out), err)
}
Terminal · recorded with Go 1.27.4
$ go run .
error: json: cannot unmarshal JSON string into Go main.Config: unknown object member name "nmae"
{"title":"deploy","at":1700000000} <nil>
What the code does
The code shows two tasks.
Task 1: read a configuration and stop with an error if the input has a name that the struct does not have. This finds typing errors in configuration files.
Task 2: write a time as Unix seconds (the number of seconds from 1 January 1970) and not as date text.
In version 1 you make a Decoder object and change its setting for task 1. For task 2 you make a new type with its own method. In version 2 you give options to the function call. Your types do not change.
Data structures
r is a reader: a source of bytes, for example a file or a network connection.
cfg is the struct that gets the data. &cfg is its address.
dec is a Decoder. It reads JSON from the reader.
unixTime is a new type made from time.Time. Its method MarshalJSON tells the JSON package how to write the value.
json.MarshalFunc(...) makes an option from a function that you write. json.WithMarshalers(unix) gives that option to one call of Marshal.
strconv.AppendInt(nil, n, 10) writes the number n as decimal text into a new slice of bytes.
Stream of tokens with jsontext
Go 1.27: read tokens, no reflection
package main
import (
"encoding/json/jsontext""fmt""io""log""strings"
)
func main() {
dec := jsontext.NewDecoder(strings.NewReader(`{"id":"a1","tags":["x","y"]}`))
for {
tok, err := dec.ReadToken()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%c %v\n", tok.Kind(), tok)
}
}
Output of the program
Terminal · recorded with Go 1.27.4
$ go run .
{ {
" id
" a1
" tags
[ [
" x
" y
] ]
} }
The example above is a complete program. The first column is the kind of the token. The second column is the token.
What the code does
The program reads JSON text one token at a time. A token is the smallest part of the text: a brace, a bracket, a name, a text value or a number.
The loop reads a token and prints its kind and its value. It stops at the end of the input. For this input it prints nine lines.
Use this method for very large files. The program does not load the full document into memory.
Data structures
dec is a jsontext.Decoder. It keeps the position in the input.
strings.NewReader(...) makes a reader from text. In a real program the reader is a file or a network connection.
tok is one token. tok.Kind() is one character that gives the kind, for example { for the start of an object and " for text.
for { ... } with no condition is a loop that continues until break.
io.EOF is a special error value. It means "end of input". log.Fatal prints an error and stops the program.
Gradual migration
Upgrade to Go 1.27. Do the tests. The v1 API now uses the v2 engine.
If an error message changed in a test, correct the test. The behavior is the same, but the text of errors can be different.
Move one package at a time to encoding/json/v2.
Where old data needs the old rules, add the v1 options from the table above to that call.
NOTE If an incompatibility stops you, build with GOEXPERIMENT=nojsonv2. This setting is temporary.
CAUTION In the last version of the experiment the tag option inline became embed. The tag options format and unknown are not in the release.
2.2
Goroutine leak profile
Preview in Go 1.26Default in Go 1.27
A leaked goroutine is blocked and nothing can unblock it. It keeps its memory until the program stops.
The new profile goroutineleak finds these goroutines. It uses the reachability data of the garbage collector. It has no cost when you do not use it.
The leak profile uses the reachability data of the garbage collector. A blocked goroutine is a leak if nothing can unblock it.
Before
// The "goroutine" profile shows ALL goroutines.// You find the leaks with your eyes.
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
// In tests, an external package compares// the goroutines before and after the test.//// import "go.uber.org/goleak"// defer goleak.VerifyNone(t)
Go 1.27
package main
import (
"errors""os""runtime/pprof""time"
)
func fetch(id int) error {
if id == 0 {
return errors.New("id 0 failed")
}
time.Sleep(10 * time.Millisecond)
return nil
}
func fetchAll(ids []int) error {
ch := make(chan error) // unbufferedfor _, id := range ids {
gofunc() { ch <- fetch(id) }()
}
forrange ids {
if err := <-ch; err != nil {
return err // the other senders block
}
}
return nil
}
func main() {
_ = fetchAll([]int{0, 1, 2, 3})
time.Sleep(100 * time.Millisecond)
// Shows only the goroutines that are leaks.
pprof.Lookup("goroutineleak").WriteTo(os.Stdout, 1)
}
Output of the program
Terminal · recorded with Go 1.27.4
$ go run .
goroutineleak profile: total 3
3 @ 0x47d88a 0x41421c 0x413e17 0x4de9d7 0x4835c1
# 0x4de9d6 main.fetchAll.func1+0x76 /home/you/go17/main.go:21
The example above is a complete program. The numbers that start with 0x and the file path are different on your computer.
What the code does
fetchAll starts one goroutine for each ID. A goroutine is a function that runs at the same time as the other code. Each goroutine calls fetch and sends the result into the channel ch.
fetchAll reads the results. ID 0 fails, and fetchAll returns at that first error. The three other goroutines still want to send their results. Nothing reads the channel, thus they wait until the program stops. This is a leak.
main waits 100 milliseconds and then prints the leak profile. The profile shows a total of 3 goroutines and the line where they wait.
The old code prints a profile of all goroutines. You must find the leaks in that list.
Data structures
ch := make(chan error) makes a channel: a pipe that goroutines use to send values to each other. This channel has no buffer. A send operation is complete only when a different goroutine receives the value.
ch <- v sends v into the channel. <-ch receives a value from it.
go func() { ... }() starts a goroutine.
[]int{0, 1, 2, 3} is a slice of four whole numbers: the IDs.
errors.New("...") makes an error value with a message. time.Sleep stops the goroutine for the given time.
pprof.Lookup(name) gets a profile: a report from the Go runtime about the program. WriteTo(os.Stdout, 1) prints it on the terminal.
To correct this leak, give the channel a buffer: ch := make(chan error, len(ids)). Then each sender completes.
NOTE In Go 1.26, build with GOEXPERIMENT=goroutineleakprofile. Without this setting, pprof.Lookup("goroutineleak") gives nil and the example panics.
shell
# In a service that imports net/http/pprof:
go tool pprof http://localhost:6060/debug/pprof/goroutineleak
What the code does
A service that imports net/http/pprof gives its profiles at a web address. This command downloads the leak profile from a service on your computer (port 6060) and opens it in the pprof tool. You do not change the service.
NOTE The profile can miss a leak if a global variable or a local variable of a runnable goroutine can get to the blocked primitive.
2.3
HTTP/1 connections stay open after Close
Go 1.27No code change
When you close an HTTP/1 response body with unread bytes, the transport now reads the small remainder in the background.
The connection goes back to the pool. The blog post gives a maximum of 5 times for sequential HTTP/1 requests.
The transport keeps the connection when the unread part is small. The limit is conservative. Large bodies still close the connection.
Before Go 1.27
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// Read the remainder. If not,// the connection is not used again.
io.Copy(io.Discard, resp.Body)
return fmt.Errorf("status %s", resp.Status)
}
Go 1.27
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// Close is sufficient for a small remainder.return fmt.Errorf("status %s", resp.Status)
}
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"fmt""net/http""net/http/httptest"
)
func get(client *http.Client, url string) error {
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// Close is sufficient for a small remainder.return fmt.Errorf("status %s", resp.Status)
}
return nil
}
func main() {
// A test server on this computer. It always answers 404.
srv := httptest.NewServer(http.NotFoundHandler())
defer srv.Close()
fmt.Println(get(srv.Client(), srv.URL))
}
Terminal · recorded with Go 1.27.4
$ go run .
status 404 Not Found
The program runs on older releases also. Only Go 1.27 uses the connection again.
What the code does
The code sends an HTTP GET request to a web address and examines the answer. If the status is not 200 (OK), the function returns an error.
In the old code you read the remainder of the answer and discard it before you return. If you do not, the client cannot use the network connection again and must open a new one. In the new code Close does this work when the remainder is small.
Data structures
client is an http.Client. It sends requests and keeps a pool of open connections.
resp is the response. resp.StatusCode is a number such as 200 or 404. resp.Status is the same data as text.
resp.Body is a stream: you read it in parts, and you must close it.
defer tells Go to do the call when the function returns. Thus the body is always closed.
io.Copy(io.Discard, resp.Body) reads all of the body and discards it.
fmt.Errorf makes an error with a message. %s is the position where the status text goes.
NOTE To stop connection reuse, set Transport.DisableKeepAlives to true.
2.4
Package uuid
Go 1.27
The standard library now makes and parses UUIDs. An external module is not necessary for the common cases.
Before: external module
import"github.com/google/uuid"
id := uuid.New() // version 4
ordered, err := uuid.NewV7() // sorts by time
parsed, err := uuid.Parse(s)
fmt.Println(id.String())
Go 1.27: standard library
import"uuid"
id := uuid.New() // good default
random := uuid.NewV4() // fully random
ordered := uuid.NewV7() // sorts by time: good for database keys
parsed, err := uuid.Parse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
fmt.Println(id.String(), ordered.Compare(random))
Complete program and output
main.go · needs Go 1.27 or later
package main
import (
"fmt""log""uuid"
)
func main() {
id := uuid.New() // good default
random := uuid.NewV4() // fully random
ordered := uuid.NewV7() // sorts by time: good for database keys
parsed, err := uuid.Parse("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
if err != nil {
log.Fatal(err)
}
fmt.Println(id.String())
fmt.Println(ordered.Compare(random))
fmt.Println(parsed)
}
Terminal · recorded with Go 1.27.4
$ go run .
21556c7d-e38a-4c6b-8f25-82dcde3a6669
-1
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
The first two lines are different in each run, because the IDs are random.
What the code does
A UUID is an identifier of 128 bits. It has sufficient random data that two UUIDs are, in practice, never the same. The text form has 36 characters.
The code makes UUIDs of different versions, reads one from text, prints one, and compares two.
The old code downloads an external module. The new code uses the standard library. One difference: uuid.NewV7() in the standard library returns no error.
Data structures
uuid.UUID is an array of 16 bytes, [16]byte. An array has a fixed length. A slice does not.
Version 4 is fully random. Version 7 starts with the current time, thus a new ID sorts after an older ID. A database index stays in sequence.
parsed, err := uuid.Parse(...) returns two results. err is not nil when the text is not a correct UUID.
Compare returns -1, 0 or +1: less than, equal, or more than.
uuid.UUID is a [16]byte. You can compare two values with ==. The type implements encoding.TextMarshaler, thus JSON operations work.
2.5
errors.AsType
Go 1.26
errors.AsType is a generic version of errors.As. It is type-safe and faster. You do not declare a target variable first.
Before Go 1.26
var pathErr *fs.PathError
if errors.As(err, &pathErr) {
fmt.Println("path:", pathErr.Path)
}
// A wrong target type causes a panic at run time.
Go 1.26
if pathErr, ok := errors.AsType[*fs.PathError](err); ok {
fmt.Println("path:", pathErr.Path)
}
// A wrong type is a compile error.
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"errors""fmt""io/fs""os"
)
func main() {
// This file does not exist, thus Open returns an error.
_, err := os.Open("/no/such/file.txt")
if pathErr, ok := errors.AsType[*fs.PathError](err); ok {
fmt.Println("path:", pathErr.Path)
}
}
Terminal · recorded with Go 1.27.4
$ go run .
path: /no/such/file.txt
What the code does
An error in Go can contain a different error. The result is a chain of errors. This code asks: is there an error of the type *fs.PathError in the chain? If yes, it prints the file path from that error.
In the old code you declare a variable first and give its address to errors.As. In the new code you write the type in square brackets. The function returns the error and a true or false value.
Data structures
err is an error value from an earlier call, for example from os.Open.
*fs.PathError is a pointer to a struct with the fields Op, Path and Err. File functions return it.
ok is a bool: true or false. It is true when the function found the type.
if x, ok := f(); ok { ... } declares variables and tests ok in one line. The variables are available only in the block.
2.6
httptest.NewTestServer with virtual time
Go 1.27
httptest.NewTestServer makes a server on an in-memory network. It works in a testing/synctest bubble.
In a bubble the clock is virtual. A handler that sleeps 30 seconds completes immediately in real time. The test is fast and not flaky.
Before Go 1.27
func TestClientTimeout(t *testing.T) {
// Real network, real clock.
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
time.Sleep(300 * time.Millisecond) // real wait
}))
defer srv.Close()
client := srv.Client()
client.Timeout = 100 * time.Millisecond // small, can be flaky
_, err := client.Get(srv.URL)
if err == nil {
t.Fatal("no timeout")
}
}
$ go test -v
=== RUN TestClientTimeout
2000/01/01 00:00:10 httptest.Server blocked in Close after 5 seconds, waiting for connections:
*nettest.Conn 0x188471626498 192.0.2.1:10001 in state active
--- PASS: TestClientTimeout (0.00s)
PASS
ok go17 0.004s
A test file has a name that ends in _test.go. You start it with go test. The log line about Close is not an error: at the end of the test the server waits for the handler, which sleeps on the virtual clock. The date in that line comes from the virtual clock. The address and the time values can be different on your computer.
What the code does
This is a test. It makes sure that a client stops when the server is too slow.
The test starts a small server. The server waits before it answers. The client has a shorter time limit. Thus client.Get must return an error. If it returns no error, the test fails.
The old test uses the real network and the real clock. It takes 300 milliseconds, and the short time limit can fail on a busy computer. The new test uses a network in memory and a virtual clock. The wait of 30 seconds takes almost no real time.
Data structures
t *testing.T is the object that the test framework gives to each test. t.Fatal stops the test and marks it as failed.
srv is the test server. srv.URL is its address. srv.Client() returns a client that can connect to it.
http.HandlerFunc(func(w, r) { ... }) is the handler: the function that the server calls for each request. r is the request. w writes the answer.
synctest.Test(t, func(t) { ... }) runs the function in a bubble. In the bubble, time moves forward only when all goroutines wait.
client.Timeout is a field of type time.Duration: the maximum time for one request.
NOTENewTestServer registers its cleanup with t.Cleanup. A nil handler gives status 500. It does not use http.DefaultServeMux.
2.7
Faster packages
Go 1.26Go 1.27No code change
These packages are faster after an upgrade. You do not change your code.
Package
Release
Result
Check after the upgrade
io.ReadAll
Go 1.26
About 2 times faster. About half of the memory.
Nothing
compress/flate
Go 1.27
Faster compression. Also for gzip, zip, zlib, png.
Compressed bytes can be different. Do not compare them with golden files.
image/jpeg
Go 1.26
Faster and more accurate encoder and decoder.
Pixels and bytes can be different. Correct tests that compare exact output.
3
Runtime and hardware
Most of these changes need no code change. You upgrade the toolchain and measure.
3.1
Green Tea garbage collector
Experiment in Go 1.25Default in Go 1.26No code change
Green Tea is the new garbage collector. It decreases the collector overhead by 10% to 40% in real programs.
On recent amd64 processors it uses AVX-512 during the scan. This gives approximately 10% more.
Green Tea changes the unit of work from one object to one page of small objects. Modern CPUs read memory in sequence much faster.
shell
# Measure the collector before and after the upgrade.
GODEBUG=gctrace=1 ./myservice 2>&1 | head
# Compare with the old collector (the setting is temporary; Go 1.27.4 still accepts it).
GOEXPERIMENT=nogreenteagc go build -o myservice-oldgc .
What the code does
The garbage collector is the part of the Go runtime that finds memory that the program does not use and makes it free.
The first command starts the program with the environment variable GODEBUG=gctrace=1. The program then prints one line for each collection. 2>&1 | head shows only the first lines. An environment variable is a setting that the shell gives to a program.
The second command builds the program with the old collector, so that you can compare the two.
3.2
SIMD packages
ExperimentGo 1.26 and Go 1.27
SIMD is one instruction that operates on many values. Go has two experimental packages.
simd/archsimd gives direct access to the vector instructions of one architecture: amd64, arm64 (NEON) and wasm.
simd is portable. The vector width is not in the type name. If the hardware has no vector unit, the package emulates the operations.
A vector register holds many elements, called lanes. The simd package hides the lane count, which is different for each CPU.
Scalar loop
// y = a*x + yfunc axpy(a float32, x, y []float32) {
for i := range x {
y[i] = a*x[i] + y[i]
}
}
Go 1.27 experiment: package simd
//go:build goexperiment.simdimport"simd"// y = a*x + yfunc axpy(a float32, x, y []float32) {
va := simd.BroadcastFloat32s(a)
n := va.Len() // lanes: different for each CPU
i := 0for ; i+n <= len(x); i += n {
vx := simd.LoadFloat32s(x[i:])
vy := simd.LoadFloat32s(y[i:])
va.MulAdd(vx, vy).Store(y[i:]) // a*x + y
}
for ; i < len(x); i++ { // remainder
y[i] = a*x[i] + y[i]
}
}
Complete program and output
main.go · needs Go 1.27 or later
//go:build goexperiment.simdpackage main
import (
"fmt""simd"
)
// y = a*x + yfunc axpy(a float32, x, y []float32) {
va := simd.BroadcastFloat32s(a)
n := va.Len() // lanes: different for each CPU
i := 0
for ; i+n <= len(x); i += n {
vx := simd.LoadFloat32s(x[i:])
vy := simd.LoadFloat32s(y[i:])
va.MulAdd(vx, vy).Store(y[i:]) // a*x + y
}
for ; i < len(x); i++ { // remainder
y[i] = a*x[i] + y[i]
}
}
func main() {
x := []float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
y := []float32{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
axpy(2, x, y)
fmt.Println(y)
}
Terminal · recorded with Go 1.27.4
$ GOEXPERIMENT=simd go run .
[3 5 7 9 11 13 15 17 19 21]
The file has a build constraint, thus go run . without GOEXPERIMENT=simd fails.
What the code does
axpy calculates y = a*x + y for each position: it multiplies each item of x by a, adds the item of y, and puts the result in y. Graphics, audio and machine learning use this operation.
The scalar loop does one item in each step. The SIMD version does many items in each step. The number of items is the lane count, n, for example 8 or 16.
The first loop takes n items at a time while sufficient items remain. The second loop does the remaining items one at a time. The result is the same as the scalar loop.
Data structures
x and y are slices of float32: numbers of 32 bits that can have a fraction.
va is a vector that holds a in each lane. A vector is a small fixed group of numbers that the CPU processes in one instruction.
vx and vy are vectors that the code loads from the slices. x[i:] is the part of x from position i to the end.
va.MulAdd(vx, vy) calculates va*vx + vy for all lanes. .Store(y[i:]) writes the result back into y.
//go:build goexperiment.simd is a build constraint. The compiler uses the file only when the experiment is on.
shell
GOEXPERIMENT=simd go run .
What the code does
The command starts the program with the SIMD experiment on. If you do not set GOEXPERIMENT=simd, the build fails.
CAUTION The API is not stable. Do not use it in production code that you cannot change quickly. The Go team plans to graduate a large subset in Go 1.28.
3.3
Slice backing stores on the stack
Go 1.26No code change
The compiler now puts the first backing store of a slice on the stack at an append site. This also applies to a slice that escapes later.
Small slices cause fewer heap allocations. You can remove capacity values that you tuned by hand.
The compiler puts a small backing store on the stack at the append site. If the slice escapes, the runtime copies it to the heap one time.
Before Go 1.26
func collect(ch <-chan task) []task {
// Manual tuning to prevent the first allocations.
tasks := make([]task, 0, 16)
for t := range ch {
tasks = append(tasks, t)
}
return tasks
}
Go 1.26
func collect(ch <-chan task) []task {
// The compiler supplies a small stack buffer.var tasks []task
for t := range ch {
tasks = append(tasks, t)
}
return tasks
}
Complete program and output
main.go · needs Go 1.26 or later
package main
import"fmt"type task struct{ id int }
func collect(ch <-chan task) []task {
// The compiler supplies a small stack buffer.var tasks []task
for t := range ch {
tasks = append(tasks, t)
}
return tasks
}
func main() {
ch := make(chan task)
// A goroutine sends five tasks and then closes the channel.gofunc() {
for i := 1; i <= 5; i++ {
ch <- task{id: i}
}
close(ch)
}()
fmt.Println(collect(ch))
}
Terminal · recorded with Go 1.27.4
$ go run .
[{1} {2} {3} {4} {5}]
What the code does
collect reads tasks from a channel until the channel is closed. It returns the tasks as a list.
In the old code the programmer makes space for 16 tasks at the start. Without this, the slice grows many times and each growth is a memory allocation. In the new code you declare an empty slice. The compiler supplies the first space.
Data structures
ch <-chan task is a channel from which this function can only receive.
for t := range ch receives values until the channel is closed.
tasks is a slice. A slice has a backing store: the block of memory that holds the items. When the block is full, append gets a larger block and copies the items.
make([]task, 0, 16) makes a slice with length 0 and space (capacity) for 16 items.
The stack is the fast memory of one function call. It becomes free when the function returns. The heap is shared memory that the garbage collector cleans. Stack memory is cheaper.
task is a type from your program. Its contents are not important here.
shell
# Measure the allocations of your function.
go test -bench=Collect -benchmem
# Stop the new stack allocations if you suspect a problem.
go build -gcflags=all=-d=variablemakehash=n ./...
What the code does
The first command runs the benchmarks with Collect in their name. A benchmark is a function in a test file that measures speed. -benchmem adds the number of memory allocations for each operation. A smaller number is better.
The second command builds the program with the new optimization off. Use it only to find out if the optimization causes a problem.
3.4
Small allocations and cgo calls
Go 1.26Go 1.27No code change
Size-specialized allocation (Go 1.27). The compiler calls a special allocator routine for each size class up to 80 bytes. These allocations are up to 30% faster. The opt-out is GOEXPERIMENT=nosizespecializedmalloc.
cgo (Go 1.26). The base overhead of each cgo call is approximately 30% smaller.
4
Security
Post-quantum cryptography by default, safer random sources, and a fast incident response.
4.1
Post-quantum key exchange in TLS
Go 1.26No code change
A future quantum computer can break classical key exchange. An attacker can record traffic today and decrypt it later.
crypto/tls now enables the hybrid key exchanges SecP256r1MLKEM768 and SecP384r1MLKEM1024 by default. The hybrid X25519MLKEM768 was a default from Go 1.24.
A hybrid key exchange is safe if one of its two parts is safe. An attacker must break the two parts.
// Default: hybrid key exchange if the server supports it.
conn, err := tls.Dial("tcp", "example.com:443", &tls.Config{})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Print the key exchange of the connection.
fmt.Println(conn.ConnectionState().CurveID)
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"crypto/tls""fmt""log"
)
func main() {
// Default: hybrid key exchange if the server supports it.
conn, err := tls.Dial("tcp", "example.com:443", &tls.Config{})
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// Print the key exchange of the connection.
fmt.Println(conn.ConnectionState().CurveID)
}
This program needs an internet connection, thus no output was recorded for example.com. The result depends on the server. In a test with a Go server on the same computer, the program printed X25519MLKEM768.
What the code does
The code opens an encrypted connection to example.com on port 443. TLS is the protocol that makes HTTPS secure. If the connection fails, the program stops. defer conn.Close() closes the connection at the end.
The code is almost the same in the two blocks. The change is in the default key exchange: the step where the two sides agree on a secret key.
The last line of the new block prints the name of the key exchange that the connection used.
Data structures
conn is a *tls.Conn: an open connection. You write bytes to it and read bytes from it.
&tls.Config{} is a struct of settings. An empty struct means: use all the defaults.
"tcp" is the network type. "example.com:443" is the host name and the port number.
conn.ConnectionState() returns a struct with data about the connection. Its field CurveID names the key exchange, for example X25519MLKEM768.
NOTE To go back, set Config.CurvePreferences or use GODEBUG=tlssecpmlkem=0. Do this only for a compatibility problem. This setting stops only the two SecP hybrids. GODEBUG=tlsmlkem=0 stops X25519MLKEM768. Two Go programs select X25519MLKEM768.
4.2
crypto/hpke
Go 1.26
HPKE (RFC 9180) encrypts a message for the holder of a public key. The package includes post-quantum hybrid KEMs.
Go 1.26: encrypt for a public key
package main
import (
"crypto/hpke""fmt""log"
)
func main() {
kem := hpke.MLKEM768X25519() // post-quantum hybrid KEM
kdf := hpke.HKDFSHA256()
aead := hpke.AES256GCM()
// Recipient: make a key pair.
priv, err := kem.GenerateKey()
if err != nil {
log.Fatal(err)
}
// Sender: encrypt for the public key.
info := []byte("orders-v1")
ct, err := hpke.Seal(priv.PublicKey(), kdf, aead, info, []byte("hello"))
if err != nil {
log.Fatal(err)
}
// Recipient: decrypt.
pt, err := hpke.Open(priv, kdf, aead, info, ct)
fmt.Println(string(pt), err)
}
Output of the program
Terminal · recorded with Go 1.27.4
$ go run .
hello <nil>
The example above is a complete program.
What the code does
The program shows public-key encryption. The recipient makes a pair of keys. The private key stays secret. The public key can go to all persons.
The sender encrypts the text hello with the public key. Only the private key can decrypt it. The program prints hello <nil>: the text, and no error.
info is a label. The two sides must use the same label. It connects the message to one purpose.
Data structures
kem, kdf and aead select three algorithms. The KEM makes a shared secret from the public key. The KDF makes keys from that secret. The AEAD encrypts the message and finds changes to it.
priv is the private key. priv.PublicKey() gives the public key that goes with it.
[]byte("hello") changes text to a slice of bytes. Encryption functions use bytes.
ct is the ciphertext: the encrypted bytes. pt is the plaintext: the bytes after decryption.
NOTE Before Go 1.26 this operation needed an external module.
4.3
crypto/mldsa
Go 1.27
ML-DSA (FIPS 204) is a post-quantum signature scheme. crypto/x509 and crypto/tls also support it.
Go now has standard post-quantum algorithms for key exchange and for signatures.
$ go run .
signature bytes: 2420
correct message: <nil>
changed message: mldsa: invalid signature
What the code does
A digital signature shows that a message came from the holder of a private key and that nobody changed it. Each block makes a key, signs a message, and examines the signature.
The classical code first calculates a digest: a short fingerprint of the message with a fixed size. Then it signs the digest. The ML-DSA code signs the message directly.
The result of the check is different. ecdsa.VerifyASN1 returns true or false. mldsa.Verify returns an error, and nil means that the signature is correct.
Data structures
priv is the private key. The public key is a part of it.
msg is the message as a slice of bytes.
digest is an array of 32 bytes. digest[:] makes a slice from the array, because the function wants a slice.
sig is the signature: a slice of bytes.
opts is a pointer to an mldsa.Options struct. Context is a label. Use the same label when you sign and when you examine.
rand.Reader is the secure source of random bytes of the system.
NOTE An ML-DSA-44 public key has 1312 bytes and a signature has 2420 bytes. An ECDSA P-256 signature has approximately 70 bytes. Plan for the size.
4.4
Secure random source in crypto
Go 1.26
Most functions that make keys or signatures now ignore the random parameter. They always use the secure random source of the system.
A weak or predictable reader cannot make a weak key. For tests that need fixed output, use testing/cryptotest.
Before Go 1.26
// The function used the reader that you gave.// A bad reader made a bad key.
priv, err := ecdsa.GenerateKey(elliptic.P256(), myReader)
// Deterministic test: a fixed reader.
priv, err = ecdsa.GenerateKey(elliptic.P256(), fixedReader)
Go 1.26
// The reader is ignored. The key is always secure.
priv, err := ecdsa.GenerateKey(elliptic.P256(), nil)
// Deterministic test: set the global source for this test.func TestSign(t *testing.T) {
cryptotest.SetGlobalRandom(t, 42)
priv, err := ecdsa.GenerateKey(elliptic.P256(), nil)
// ...
}
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"crypto/ecdsa""crypto/elliptic""fmt""log"
)
func newKey() *ecdsa.PrivateKey {
// The reader is ignored. The key is always secure.
priv, err := ecdsa.GenerateKey(elliptic.P256(), nil)
if err != nil {
log.Fatal(err)
}
return priv
}
func main() {
a, b := newKey(), newKey()
fmt.Println("same key:", a.Equal(b))
}
key_test.go · needs Go 1.26 or later
package main
import (
"testing""testing/cryptotest"
)
func TestKey(t *testing.T) {
// Deterministic test: set the global source for this test.
cryptotest.SetGlobalRandom(t, 42)
b, err := newKey().Bytes()
if err != nil {
t.Fatal(err)
}
t.Logf("key starts with %x", b[:4])
}
Terminal · recorded with Go 1.27.4
$ go run .
same key: false
$ go test -v
=== RUN TestKey
key_test.go:16: key starts with 22301fb8
--- PASS: TestKey (0.00s)
PASS
ok go17 0.002s
go test prints the same key bytes in each run, because the seed is fixed. go run . makes two different keys.
What the code does
The code makes an ECDSA key. The second argument of GenerateKey is a source of random bytes.
In the old code the function used the source that you gave. A weak source made a weak key. Tests used a fixed source to get the same key each time.
In the new code the function ignores the argument. You can give nil. It always uses the secure source of the system. A test that needs the same key each time calls cryptotest.SetGlobalRandom. This call applies only to that one test.
Data structures
myReader and fixedReader are readers: values that supply bytes.
priv is a pointer to an ecdsa.PrivateKey.
elliptic.P256() names the curve: the mathematical parameters of the key.
t *testing.T is the object of the test. The number 42 is the seed. The same seed gives the same random bytes.
NOTEGODEBUG=cryptocustomrand=1 brings back the old behavior for a limited time.
4.5
Runtime hardening
Go 1.26Experiment
Heap base address. On 64-bit systems the runtime gives the heap a random base address at start. This makes memory attacks on cgo programs more difficult.
runtime/secret. This experimental package erases temporary secret data from registers, the stack and the heap. It supports amd64 and arm64 on Linux.
Go 1.26 experiment: GOEXPERIMENT=runtimesecret
//go:build goexperiment.runtimesecretimport"runtime/secret"var sessionKey []byte
func handshake(priv *ecdh.PrivateKey, peer *ecdh.PublicKey) {
secret.Do(func() {
shared, err := priv.ECDH(peer) // temporary secretif err != nil {
return
}
sessionKey = deriveKey(shared)
})
// The runtime erased the temporaries of the function.
}
Complete program and output
main.go · needs Go 1.26 or later
//go:build goexperiment.runtimesecretpackage main
import (
"crypto/ecdh""crypto/rand""crypto/sha256""fmt""log""runtime/secret"
)
var sessionKey []byte
func deriveKey(shared []byte) []byte {
sum := sha256.Sum256(shared)
return sum[:]
}
func handshake(priv *ecdh.PrivateKey, peer *ecdh.PublicKey) {
secret.Do(func() {
shared, err := priv.ECDH(peer) // temporary secretif err != nil {
return
}
sessionKey = deriveKey(shared)
})
// The runtime erased the temporaries of the function.
}
func main() {
// Two key pairs: this side and the other side.
mine, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
log.Fatal(err)
}
theirs, err := ecdh.X25519().GenerateKey(rand.Reader)
if err != nil {
log.Fatal(err)
}
handshake(mine, theirs.PublicKey())
fmt.Println("session key bytes:", len(sessionKey))
}
Terminal · recorded with Go 1.27.4
$ GOEXPERIMENT=runtimesecret go run .
session key bytes: 32
The file has a build constraint, thus you must set GOEXPERIMENT=runtimesecret.
What the code does
Two sides calculate a shared secret from a private key and the public key of the other side. Then they make a session key from it.
The shared secret is temporary. It must not stay in memory, where a later defect or a crash report can show it. secret.Do runs the function and then erases the data that the function left in the CPU registers, on the stack and on the heap.
The session key stays, because the program continues to use it.
Data structures
priv is a pointer to a private key. peer is a pointer to the public key of the other side.
shared is a slice of bytes: the temporary secret.
sessionKey is a package-level variable. It is declared outside all functions and exists for the full life of the program.
func() { ... } is a function with no name. It can use the variables of the function around it, here priv and peer.
deriveKey is a function from your program. It is not shown.
4.6
The eMudhra incident and govulncheck
October 2026
In October, eight intermediate certificates of a trusted root CA had weak private keys. The certificates were for TLS and for code signing.
Linux has no common revocation mechanism in the operating system. Thus the TLS verifier of Go is an important defense.
The fix was available before the public disclosure of the keys.
Do this procedure to make sure that your programs have the fix.
Install the tool: go install golang.org/x/vuln/cmd/govulncheck@latest
Examine the source: govulncheck ./...
Examine a binary that is in service: govulncheck -mode=binary ./bin/myservice
If the tool reports the standard library, upgrade the toolchain to Go 1.27.3 or later: go get toolchain@go1.27.3. On the Go 1.26 line, use go1.26.10 or later.
Build the program again and deploy it.
NOTEgopls now starts govulncheck automatically when the dependencies in go.mod change.
5
Tools
The top problem in the 2025 developer survey was to follow current idioms. The tools now do this work.
5.1
go fix and the modernizers
Go 1.26
Go 1.26 has a fully rebuilt go fix command. It has dozens of modernizers. A modernizer finds an old idiom and replaces it with the current one.
The fixes do not change the behavior of the program. gopls shows the same fixes as suggestions in the editor.
One analyzer, three tools. The go fix command applies the fixes that gopls shows as suggestions.
Commit your work. A clean tree shows the changes clearly.
Show the changes without a write operation: go fix -diff ./...
Apply the changes: go fix ./...
Do the tests: go test ./...
Do go fix again. One fix can make a second fix possible.
Old idioms
func larger(a, b int) int {
x := a
if b > a {
x = b
}
return x
}
func has(xs []string, want string) bool {
for _, x := range xs {
if x == want {
return true
}
}
return false
}
func runAll(jobs []func()) {
var wg sync.WaitGroup
for i := 0; i < len(jobs); i++ {
wg.Add(1)
gofunc() {
defer wg.Done()
jobs[i]()
}()
}
wg.Wait()
}
var cache map[string]interface{}
Result of go fix
func larger(a, b int) int {
x := max(b, a) // minmaxreturn x
}
func has(xs []string, want string) bool {
return slices.Contains(xs, want) // slicescontains
}
func runAll(jobs []func()) {
var wg sync.WaitGroup
for i := range jobs { // rangeint
wg.Go(func() { // waitgroup
jobs[i]()
})
}
wg.Wait()
}
var cache map[string]any // any
Complete program and output
main.go · needs Go 1.26 or later
package main
import (
"fmt""sync"
)
func larger(a, b int) int {
x := a
if b > a {
x = b
}
return x
}
func has(xs []string, want string) bool {
for _, x := range xs {
if x == want {
return true
}
}
return false
}
func runAll(jobs []func()) {
var wg sync.WaitGroup
for i := 0; i < len(jobs); i++ {
wg.Add(1)
gofunc() {
defer wg.Done()
jobs[i]()
}()
}
wg.Wait()
}
var cache map[string]interface{}
func main() {
fmt.Println(larger(3, 8))
fmt.Println(has([]string{"a", "b"}, "b"))
runAll([]func(){func() { fmt.Println("job done") }})
fmt.Println(len(cache))
}
Terminal · recorded with Go 1.27.4
$ go run .
8
true
job done
0
$ go fix ./...
$ go run .
8
true
job done
0
$ cat main.go
package main
import (
"fmt"
"slices"
"sync"
)
func larger(a, b int) int {
x := max(b, a)
return x
}
func has(xs []string, want string) bool {
return slices.Contains(xs, want)
}
func runAll(jobs []func()) {
var wg sync.WaitGroup
for i := range jobs {
wg.Go(func() {
jobs[i]()
})
}
wg.Wait()
}
var cache map[string]any
func main() {
fmt.Println(larger(3, 8))
fmt.Println(has([]string{"a", "b"}, "b"))
runAll([]func(){func() { fmt.Println("job done") }})
fmt.Println(len(cache))
}
The program prints the same four lines before and after go fix. The last command shows the file that go fix wrote.
What the code does
The left block has four pieces of code in an old style. The right block is the result of go fix. The behavior is the same and the code is shorter.
larger returns the larger of two numbers. The tool uses the built-in function max.
has looks for a text value in a list. The tool uses slices.Contains.
runAll starts each job in its own goroutine and waits until all are complete. The tool uses wg.Go and a shorter loop.
interface{} becomes any. The two words have the same meaning: a value of any type.
Data structures
xs []string is a slice of text values.
jobs []func() is a slice of functions that have no inputs and no results.
sync.WaitGroup counts goroutines that are in operation. Add(1) increases the count. Done() decreases it. Wait() stops until the count is zero. wg.Go(f) does Add, starts f in a goroutine, and does Done at the end.
for i := 0; i < len(jobs); i++ is a loop with three parts: the start, the condition and the step.
map[string]any is a map: a table that finds a value from a key. Here the keys are text and the values can have any type.
minmax does not change each form. For example, it does not change if v < lo { v = lo }.
The Go 1.27 release notes name four new modernizers: atomictypes, embedlit, slicesbackward and unsafefuncs. Go 1.27.4 also has errorsastype. Go 1.27 gives waitgroup the new name waitgroupgo and removes fmtappendf. To see the list, do go tool fix help.
New language proposals can now include a modernizer. This is important for AI assistants, because their training data contains old Go code.
5.2
The source-level inliner
Go 1.26
A package author can move the callers of a deprecated API automatically. The author adds the comment //go:fix inline to the old function, type or constant.
go fix then replaces each call with the body of the function. It keeps the evaluation sequence, the side effects and the names correct.
The package has an old function, New, and a newer function, NewWithTimeout. New only calls the newer function with a time limit of 30 seconds.
The comment // Deprecated: tells persons and tools not to use New. The comment //go:fix inline tells go fix to replace each call of New with the body of New.
Data structures
*Client is a pointer to a Client struct. The struct is not shown.
addr string is the address of the server as text.
30*time.Second is a time.Duration of 30 seconds.
//go:fix inline is a directive: a comment with no space after // that a tool reads.
Caller, before go fix
c := client.New("db:5432")
Caller, after go fix
c := client.NewWithTimeout("db:5432", 30*time.Second)
package main
import (
"fmt""go17/client"
)
func main() {
c := client.New("db:5432")
fmt.Println(c.Addr, c.Timeout)
}
Terminal · recorded with Go 1.27.4
$ go run .
db:5432 30s
$ go fix ./...
$ go run .
db:5432 30s
$ cat main.go
package main
import (
"fmt"
"time"
"go17/client"
)
func main() {
c := client.NewWithTimeout("db:5432", 30*time.Second)
fmt.Println(c.Addr, c.Timeout)
}
Put client.go in a directory with the name client. The module name must be go17, as in "Prepare a work area". The program prints the same line before and after go fix.
What the code does
These two blocks show one line in the code of a caller, before and after go fix.
The tool replaced the call with the body of New. It put the argument "db:5432" in the position of addr. It also added the import of the package time. The program does the same work as before.
Data structures
c is a pointer to a client.Client: the object that the program uses to speak to the database server at db:5432.
NOTE The standard library uses the same directive. For example, calls to ioutil.ReadFile become os.ReadFile.
5.3
gopls
v0.21 to v0.24
gopls had four releases. The largest change is interactive refactoring. This is an open extension of the Language Server Protocol. The Go team and the Dart team made it together.
With this extension a refactoring can ask you questions in more than one step.
Task
Before
Now
Add or remove struct tags
Fixed result, or manual edit
A dialog lets you select the tags and the name style
Implement an interface
Write the method stubs by hand, or use an external tool
Live search for the interface. Generic interfaces work.
Move a declaration to a different package
Cut, paste, correct the imports
One refactoring
Rename a package
Limited to one directory
Works across directories
Edit Go assembly files
Configuration necessary
No configuration
Examine a part of an expression
Hover showed the full expression
Hover shows the subexpression
Promoted fields
No help
Completions and inlay hints
Vulnerabilities
You start govulncheck
Automatic scan when go.mod dependencies change
gopls also has a built-in Model Context Protocol (MCP) server. An AI assistant uses it to ask gopls about your workspace. Work on this server continues.
shell
# Get the current gopls.
go install golang.org/x/tools/gopls@latest
gopls version
What the code does
gopls is the program that gives your editor its knowledge of Go: completions, error marks and refactoring. The first command downloads the newest version, builds it and installs it. The second command prints the version.
5.4
pkg.go.dev API and go doc
May 2026Go 1.27
pkg.go.dev now has an official API. It gives module versions, package symbols, importers and vulnerability data.
Tools and AI agents can read correct package data. They do not parse HTML pages.
go doc in Go 1.27 shows the documentation of a specified package version.
Before Go 1.27
# Only the version in your go.mod or the standard library.
go doc golang.org/x/sync/errgroup
# For a different version: open pkg.go.dev in a browser,# or download the module first.
Go 1.27
# A specified version, from the command line.
go doc golang.org/x/sync/errgroup@v0.10.0
# List the examples of a package, then print one.
go doc -ex bytes
go doc bytes.ExampleBuffer
What the code does
go doc prints the documentation of a package or of one name in the terminal.
golang.org/x/sync/errgroup is a package in a module. A module is a set of packages with one version number. In Go 1.27 you can add @v0.10.0 to select a version.
go doc -ex bytes adds the list of examples of the package bytes. go doc bytes.ExampleBuffer prints the source code of one example.
6
Plans for the next year
These items are plans. They can change before a release.
6.1
Language and library
Go 1.28Proposal
Composite literals without the redundant type. Go 1.28 plans to let you omit the type when the context gives it (issue 12854).
The code that follows is an illustration of the idea. It is not the final syntax.
func drawLine(from, to Point) { /* ... */ }
// Illustration only. The parameter type gives Point.
drawLine({0, 0}, {10, 10})
What the code does
drawLine accepts two points. The call draws a line from the point (0, 0) to the point (10, 10).
Today you write the type name Point before each pair of braces. The idea for Go 1.28 is to omit the name, because the function declaration already gives the type. The second block does not compile in Go 1.26 or Go 1.27.
Data structures
Point is a struct with two number fields, for example X and Y. It is not shown.
Point{0, 0} is a composite literal. It makes a struct value and gives the field values in sequence.
Generic collections. Sets, ordered maps and more are accepted proposals (issue 80590). They go into golang.org/x/exp first. Later they can go into the standard library.
6.2
Runtime, toolchain and community
Plan
Area
Plan
SIMD
Go 1.28: graduate a large subset of simd and simd/archsimd for amd64, arm64 NEON and wasm. Go 1.29: arm64 scalable vectors (SVE).
Memory
Decrease the memory footprint of Go programs. This is a high priority because of the global RAM shortage.
Build speed
Go 1.28: write compiler export data earlier, for more parallel builds (issue 15734).
Static analysis
Go 1.28: separate the export data for tools from the compiler (issue 79427). Let teams add their own analyzers (issue 82464).
cgo
Builds without a C toolchain (issue 81450).
WebAssembly
Evaluate the stack-switching extension. Early results show better speed and smaller binaries.
pkg.go.dev
More signals for package health and quality, on the site and in the API.
Proposal process
New structure for more throughput and visibility. The community gets a formal role in triage and review (issue 80580).
Contributors
A contributor ladder with more autonomy. Maintainer summits open to trusted contributors.
7
Upgrade checklist
One sequence for the upgrade to Go 1.27, and the switches that bring back an old behavior.
7.1
Procedure
Go 1.27
Do the steps in this sequence. Each step refers to the section that gives the details.
Install Go 1.27 or later. Make sure with go version.
Set the language version of the module: go mod edit -go=1.27. The new language features of section 1 need this line. With go 1.26 in go.mod, the Go 1.27 compiler rejects them.
Build and examine the code: go build ./... && go vet ./...
Do the tests: go test ./.... If a test compares exact output, look at these three causes first: the text of JSON errors (section 2.1), compressed bytes (section 2.7) and JPEG data (section 2.7).
Find tests that give a fixed random reader to a crypto function. Change them to cryptotest.SetGlobalRandom (section 4.4).
Show the modernizer changes with go fix -diff ./.... Apply them with go fix ./.... Do the tests again (section 5.1).
Examine the code for known vulnerabilities: govulncheck ./... (section 4.6).
Measure. Do your benchmarks with go test -bench=. -benchmem and compare with the values before the upgrade (sections 3.1 and 3.3).
If a step fails, use one switch from section 7.2 to find the cause. Remove the switch when the cause is corrected.
7.2
Switches that bring back an old behavior
Go 1.26Go 1.27
There are three types of switch. You set GOEXPERIMENT when you build the program. You set GODEBUG when you start the program. A -gcflags value is an argument of go build.
All these switches are temporary. Use them to find a problem, not as a permanent setting.
Switch
Old behavior that comes back
Section
Result of the check for this guide
GOEXPERIMENT=nojsonv2
The old engine of encoding/json
2.1
Go 1.27.4 built and ran the version 1 example.
GOEXPERIMENT=nogreenteagc
The garbage collector from before Green Tea
3.1
Go 1.26.6 and Go 1.27.4 accepted the setting. The check did not confirm which collector the program used.
GOEXPERIMENT=nosizespecializedmalloc
The general allocator for small objects. The release notes expect the removal of this switch in Go 1.28.
3.4
Go 1.27.4 built and ran a program.
-gcflags=all=-d=variablemakehash=n
No slice backing stores on the stack
3.3
The slice in the example needed 4 allocations with the switch and 1 without it.
GODEBUG=tlssecpmlkem=0
No SecP256r1MLKEM768 and no SecP384r1MLKEM1024 in TLS
4.1
The program ran. Two Go programs continued to use X25519MLKEM768.
GODEBUG=tlsmlkem=0
No X25519MLKEM768 in TLS
4.1
The connection used X25519.
GODEBUG=cryptocustomrand=1
Crypto functions use the random reader that you give
4.4
A fixed reader gave the same key two times. Without the switch the keys were different.
8
More changes in Go 1.27
These changes are in the Go 1.27 release notes. They are not in the birthday post.
8.1
Small additions to the standard library
Go 1.27
The example shows two of the additions. The list below it gives more.
main.go · needs Go 1.27 or later
package main
import (
"fmt""net/url""strings"
)
func main() {
// strings.CutLast divides text at the LAST separator.
dir, file, found := strings.CutLast("/var/log/app/server.log", "/")
fmt.Println(dir, file, found)
// URL.Clone makes a full copy. A change to the copy// does not change the original.
u, _ := url.Parse("https://example.com/search?q=go")
c := u.Clone()
c.Path = "/docs"
fmt.Println(u)
fmt.Println(c)
}
Terminal · recorded with Go 1.27.4
$ go run .
/var/log/app server.log true
https://example.com/search?q=go
https://example.com/docs?q=go
What the code does
The first part divides a file path into the directory and the file name. strings.CutLast looks for the last /. It returns the text before it, the text after it, and true because it found the separator. The older function strings.Cut uses the first separator.
The second part reads a web address into a URL value and makes a copy with Clone. The program changes the path of the copy. The output shows that the original did not change.
Data structures
dir, file and found are three results of one function call. Go functions can return more than one value.
u is a pointer to a url.URL: a struct with the parts of a web address, for example Scheme, Host, Path and RawQuery.
c is a pointer to a second, independent url.URL. If you write c := u, the two names point to the same struct, and a change through c also changes u. Clone prevents that.
u, _ := discards the error result of url.Parse. In a real program, examine the error.
bytes.CutLast does the same as strings.CutLast for slices of bytes.
url.Values.Clone makes a full copy of a set of query parameters.
synctest.Sleep in testing/synctest does a sleep and then waits until the other goroutines of the bubble are blocked.
hash/maphash has the new interfaces Hasher and ComparableHasher. They are the base for the generic collections of section 6.1.
math/big has Int.Divide. It returns the quotient and the remainder with a rounding mode that you select.
database/sql has ConvertAssign. Drivers can use the conversions of Rows.Scan.
crypto/tls accepts MLKEM1024 in Config.CurvePreferences. Config.Rand is deprecated. Use cryptotest.SetGlobalRandom in tests.
net/http has Server.MaxHeaderValueCount. The HTTP/2 server obeys the priorities that the client sends. Server.DisableClientPriority stops this.
The package unicode uses Unicode 17.
NOTE Only the example was run for this guide. The items in the list come from the release notes.
8.2
Tools, runtime and platforms
Go 1.27
Area
Change
What you do
go mod tidy
For a module with go 1.27 or later, it merges duplicate require blocks. The result has a maximum of two blocks: direct and indirect dependencies.
Expect one change in go.mod. Commit it.
go test
It runs the stdversion check of go vet. The check finds standard library names that are newer than the go version of the file.
Increase the go version, or do not use the newer name.
go vet
The printf check reports fmt.Errorf with %w and a pointer *E when E implements error. Such an error does not match in errors.Is.
Give the value, not the pointer. This check was run for this guide and gave the report.
gofmt
The column alignment is now the same on all CPU architectures.
Do gofmt one time. Small space changes are possible.
go tool trace
-http=:port listens only on localhost.
For all interfaces, give an address: -http=0.0.0.0:6060.
Tracebacks
For a module with go 1.27 or later, the first line of each goroutine in a traceback includes its runtime/pprof labels.
GODEBUG=tracebacklabels=0 stops this. A short test for this guide did not show the labels, thus this item is not confirmed.
Timers
The setting asynctimerchan is removed. The channels of time are always unbuffered.
Remove the setting from go.mod and from //go:debug lines.
TLS settings
These GODEBUG settings are removed: tlsunsafeekm, tlsrsakex, tls3des, tls10server and x509keypairleaf.
Remove them. The new behavior is permanent.
Function literals
Two function literals that are the same can use the same code.
Do not compare function pointers.
Version control
The go command does not get modules from Bazaar (bzr) servers.
Move such modules to a different host or use a module proxy.
macOS
Go 1.27 needs macOS 13 or later.
Upgrade build computers that have an older macOS.
linux/ppc64
Binaries use the ELFv2 ABI. They need Linux kernel 3.13 or later.
Make sure that C libraries are ELFv2.
9
Credits
The persons and teams that the birthday post names.
Work
Credit
The birthday post
Austin Clements, for the Go team
encoding/json/v2 and jsontext
Joe Tsai, Daniel Martí and the Go community
Goroutine leak profile
Vlad Saioc and the Programming Systems team of Uber. The method comes from research at Aarhus University and Washington University in St. Louis.
Interactive refactoring in the Language Server Protocol