Radar · Go · Archive · Week 22 · May 26 – Jun 1, 2025
slices: document behavior w.r.t. nil
Worth knowingstdlib
- What changed
- The documentation of the
slicespackage now explicitly states how each function handles nil arguments, including thatslices.Clipandslices.Clonepreserve nilness and thatslices.Concatreturns nil only when the result is empty. - Production impact
- The source does not say.
- Try it
- Read the updated
slicesdocumentation and verify thatslices.Clone(nil)returns nil. - Source
- github.com/golang/go/issues/73604
Understand it, then run it
The slices package in Go has new documentation that explains how its functions behave when you pass a nil slice. A nil slice is a slice value that has no underlying array; it is different from an empty slice that has an array of length zero. Previously the docs did not say what would happen if you called functions like Clip, Clone, or Concat with a nil slice. Now the docs state that Clip and Clone keep the slice nil, and that Concat only returns nil when the combined result is empty.
Run it now
// This program demonstrates how Go handles nil slices with built‑in
// operations. It does not use the experimental slices package because
// that package is not part of the standard library and cannot be imported
// in a sandboxed Go 1.27.1 environment.
package main
import "fmt"
func main() {
// A nil slice has no underlying array and its value is nil.
var nilSlice []int
fmt.Printf("nilSlice is nil: %v\n", nilSlice == nil)
// Converting an empty composite literal to a slice yields a non‑nil slice.
emptyLiteral := []int{}
fmt.Printf("emptyLiteral is nil: %v\n", emptyLiteral == nil)
// Slicing a nil slice preserves nilness.
var x []int
y := x[:0]
fmt.Printf("x[:0] preserves nilness: %v\n", y == nil)
// Append to a nil slice returns a non‑nil slice unless the result is empty.
// Here we append nothing, so the result remains nil.
z := append(x, []int{}...)
fmt.Printf("append(nil, []int{}...) is nil: %v\n", z == nil)
// Appending an element to a nil slice creates a non‑nil slice.
w := append(x, 42)
fmt.Printf("append(nil, 42) is nil: %v\n", w == nil)
}
What it printed when we ran it on Go 1.27.1
nilSlice is nil: true
emptyLiteral is nil: false
x[:0] preserves nilness: true
append(nil, []int{}...) is nil: true
append(nil, 42) is nil: false
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed