or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

apidiff.mdconstraints.mdebnf.mderrors.mdevent.mdgorelease.mdindex.mdio-i2c.mdio-spi.mdjsonrpc2.mdmaps.mdmmap.mdmodgraphviz.mdrand.mdshiny.mdslices.mdslog.mdstats.mdsumdb.mdtrace.mdtxtar.mdtypeparams.mdutf8string.md
tile.json

index.mddocs/

golang.org/x/exp

golang.org/x/exp is an experimental repository containing packages that extend Go's standard library with additional functionality. These packages serve as a staging area for features that may eventually be promoted to the main Go repository, though some remain experimental indefinitely. The repository includes utilities for generic programming, API compatibility checking, structured logging, statistical analysis, random number generation, parsing, I/O operations, and more.

Note: Packages in this repository are not subject to Go 1 compatibility promises and may change or be removed without notice.

Package Information

  • Package Name: golang.org/x/exp
  • Package Type: golang
  • Language: Go
  • Installation: go get golang.org/x/exp/<package-name>

Core Imports

Import specific packages as needed:

import (
    "golang.org/x/exp/constraints"
    "golang.org/x/exp/slices"
    "golang.org/x/exp/maps"
    "golang.org/x/exp/slog"
    "golang.org/x/exp/stats"
)

Basic Usage

package main

import (
    "fmt"
    "golang.org/x/exp/slices"
    "golang.org/x/exp/maps"
    "golang.org/x/exp/constraints"
)

// Generic function using constraints
func Min[T constraints.Ordered](a, b T) T {
    if a < b {
        return a
    }
    return b
}

func main() {
    // Using slices package
    numbers := []int{3, 1, 4, 1, 5, 9, 2, 6}
    slices.Sort(numbers)
    fmt.Println(numbers) // [1 1 2 3 4 5 6 9]

    // Using maps package
    m := map[string]int{"a": 1, "b": 2, "c": 3}
    keys := maps.Keys(m)
    fmt.Println(keys) // [a b c] (in indeterminate order)

    // Using generic constraint
    result := Min(10, 20)
    fmt.Println(result) // 10
}

Capabilities

Generic Programming & Type Utilities

Type constraints and utilities for working with generic types in Go.

constraints - Standard type constraints for generic programming:

// Ordered permits any type that supports comparison operators
type Ordered = cmp.Ordered

// Integer permits any integer type
type Integer interface {
    Signed | Unsigned
}

// Signed permits any signed integer type
type Signed interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

// Unsigned permits any unsigned integer type
type Unsigned interface {
    ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

// Float permits any floating-point type
type Float interface {
    ~float32 | ~float64
}

// Complex permits any complex numeric type
type Complex interface {
    ~complex64 | ~complex128
}

slices - Generic operations for working with slices:

// Sorting and searching
func Sort[S ~[]E, E cmp.Ordered](x S)
func BinarySearch[S ~[]E, E cmp.Ordered](x S, target E) (int, bool)

// Comparison and testing
func Equal[S ~[]E, E comparable](s1, s2 S) bool
func Contains[S ~[]E, E comparable](s S, v E) bool

// Manipulation
func Clone[S ~[]E, E any](s S) S
func Insert[S ~[]E, E any](s S, i int, v ...E) S
func Delete[S ~[]E, E any](s S, i, j int) S
func Compact[S ~[]E, E comparable](s S) S
func Reverse[S ~[]E, E any](s S)

// Finding values
func Index[S ~[]E, E comparable](s S, v E) int
func Max[S ~[]E, E cmp.Ordered](x S) E
func Min[S ~[]E, E cmp.Ordered](x S) E

maps - Generic operations for working with maps:

// Creation and copying
func Clone[M ~map[K]V, K comparable, V any](m M) M
func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)

// Comparison
func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](
    m1 M1, m2 M2, eq func(V1, V2) bool) bool

// Extraction
func Keys[M ~map[K]V, K comparable, V any](m M) []K
func Values[M ~map[K]V, K comparable, V any](m M) []V

// Modification
func Clear[M ~map[K]V, K comparable, V any](m M)
func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)

Maps Documentation Slices Documentation Constraints Documentation

API Analysis & Compatibility

Tools for detecting API changes and ensuring compatibility between package versions.

apidiff - Analyze API differences between package versions:

type Change struct {
    Message    string
    Compatible bool
}

type Report struct {
    Changes []Change
}

// Compare two package versions
func Changes(old, new *types.Package) Report

// Compare two modules
func ModuleChanges(old, new *Module) Report

// Output methods
func (r Report) String() string
func (r Report) Text(w io.Writer) error
func (r Report) TextIncompatible(w io.Writer, withHeader bool) error

The apidiff package detects breaking changes in Go packages by comparing type definitions, function signatures, and exported APIs. It classifies changes as either compatible (e.g., adding new exports) or incompatible (e.g., removing exports, changing signatures).

API Compatibility Tools

Logging (slog)

Structured logging with support for different output formats and log levels.

slog - Structured logging framework:

type Logger struct { /* ... */ }

// Create loggers with different handlers
func New(h Handler) *Logger
func NewTextHandler(w io.Writer, opts *HandlerOptions) Handler
func NewJSONHandler(w io.Writer, opts *HandlerOptions) Handler

// Logging methods
func (l *Logger) Debug(msg string, args ...any)
func (l *Logger) Info(msg string, args ...any)
func (l *Logger) Warn(msg string, args ...any)
func (l *Logger) Error(msg string, args ...any)
func (l *Logger) Log(ctx context.Context, level Level, msg string, args ...any)

// Context-aware logging
func (l *Logger) With(args ...any) *Logger
func (l *Logger) WithGroup(name string) *Logger

// Top-level functions (use default logger)
func Debug(msg string, args ...any)
func Info(msg string, args ...any)
func Warn(msg string, args ...any)
func Error(msg string, args ...any)

// Configuration
func SetDefault(l *Logger)

// Attributes
func String(key, value string) Attr
func Int(key string, value int) Attr
func Bool(key string, value bool) Attr
func Any(key string, value any) Attr
func Group(key string, args ...any) Attr
type HandlerOptions struct {
    AddSource   bool
    Level       Leveler
    ReplaceAttr func(groups []string, a Attr) Attr
}

type Level int

const (
    LevelDebug Level = -4
    LevelInfo  Level = 0
    LevelWarn  Level = 4
    LevelError Level = 8
)

slog provides structured logging where each log record includes a message, severity level, and key-value attributes. It supports JSON and text output formats, dynamic log levels, and attribute grouping.

Structured Logging Details

Error Handling

Enhanced error handling utilities beyond the standard library.

The errors package (not exported in main API reference) provides utilities for wrapping and inspecting errors with additional context.

Error Handling Details

JSON-RPC 2.0

Complete implementation of the JSON-RPC 2.0 specification.

jsonrpc2 - JSON-RPC 2.0 protocol implementation:

type Connection struct { /* ... */ }

// Create connections
func Dial(ctx context.Context, dialer Dialer, binder Binder) (*Connection, error)

// Make RPC calls
func (c *Connection) Call(ctx context.Context, method string, params interface{}) *AsyncCall
func (c *Connection) Notify(ctx context.Context, method string, params interface{}) error
func (c *Connection) Respond(id ID, result interface{}, rerr error) error

// Wait for results
func (a *AsyncCall) Await(ctx context.Context, result interface{}) error
func (a *AsyncCall) IsReady() bool

// Handler interface
type Handler interface {
    Handle(ctx context.Context, req *Request) (interface{}, error)
}

type Request struct {
    ID     ID
    Method string
    Params json.RawMessage
}
// Error codes
var (
    ErrUnknown        = NewError(-32001, "JSON RPC unknown error")
    ErrParse          = NewError(-32700, "JSON RPC parse error")
    ErrInvalidRequest = NewError(-32600, "JSON RPC invalid request")
    ErrMethodNotFound = NewError(-32601, "JSON RPC method not found")
    ErrInvalidParams  = NewError(-32602, "JSON RPC invalid params")
    ErrInternal       = NewError(-32603, "JSON RPC internal error")
)

func NewError(code int64, message string) error

jsonrpc2 provides a minimal but complete implementation of JSON-RPC 2.0, supporting both client and server operations, multiple framing formats (header-based and raw), and async operations.

JSON-RPC 2.0 Details

Tracing & Events

Execution tracing and event collection for performance analysis.

trace - Flight recorder for collecting execution traces:

type FlightRecorder struct { /* ... */ }

func NewFlightRecorder() *FlightRecorder

type Reader struct { /* ... */ }

func NewReader(r io.Reader) (*Reader, error)

// Read events from trace
func (r *Reader) ReadEvent() (Event, error)

type Event struct { /* ... */ }

func (e Event) Kind() EventKind
func (e Event) Time() Time
func (e Event) Goroutine() GoID
func (e Event) Stack() Stack
type EventKind uint16

const (
    EventBad EventKind = iota
    EventSync
    EventMetric
    EventLabel
    EventStackSample
    EventRangeBegin
    EventRangeEnd
    EventLog
    EventStateTransition
    EventExperimental
)

The trace package provides a mechanism to collect and retrieve recent execution data without keeping complete trace history, similar to a flight recorder.

Event System Details Tracing Details

I/O & Hardware

Low-level I/O interfaces for hardware devices (deprecated, use periph.io instead).

mmap - Memory-mapped file I/O:

type ReaderAt struct { /* ... */ }

func Open(filename string) (*ReaderAt, error)

func (r *ReaderAt) ReadAt(p []byte, off int64) (int, error)
func (r *ReaderAt) At(i int) byte
func (r *ReaderAt) Len() int
func (r *ReaderAt) Close() error

i2c (deprecated) - I2C device communication:

type Device struct { /* ... */ }

func Open(o driver.Opener, addr int) (*Device, error)

func (d *Device) Read(buf []byte) error
func (d *Device) Write(buf []byte) error
func (d *Device) ReadReg(reg byte, buf []byte) error
func (d *Device) WriteReg(reg byte, buf []byte) error
func (d *Device) Close() error

spi (deprecated) - SPI device communication:

type Device struct { /* ... */ }

func Open(o driver.Opener) (*Device, error)

func (d *Device) Tx(w, r []byte) error
func (d *Device) SetMode(mode Mode) error
func (d *Device) SetMaxSpeed(speed int) error
func (d *Device) Close() error

const (
    Mode0 = Mode(0)
    Mode1 = Mode(1)
    Mode2 = Mode(2)
    Mode3 = Mode(3)
)

Note: The i2c and spi packages are deprecated. Use https://periph.io/ for production I/O operations.

I2C Device Communication SPI Device Communication Memory-Mapped Files

Parsing & Language Tools

Tools for parsing and working with EBNF grammars.

ebnf - EBNF grammar parser and verifier:

type Grammar map[string]*Production

func Parse(filename string, src io.Reader) (Grammar, error)
func Verify(grammar Grammar, start string) error

type Production struct {
    Name *Name
    Expr Expression
}

type Expression interface {
    Pos() scanner.Position
}

// Expression types
type Alternative []Expression
type Sequence []Expression
type Group struct {
    Lparen scanner.Position
    Body   Expression
}
type Option struct {
    Lbrack scanner.Position
    Body   Expression
}
type Repetition struct {
    Lbrace scanner.Position
    Body   Expression
}
type Token struct {
    StringPos scanner.Position
    String    string
}
type Name struct {
    StringPos scanner.Position
    String    string
}

The ebnf package parses EBNF (Extended Backus-Naur Form) grammars and verifies their consistency. It includes a command-line tool (ebnflint) for validating grammars in HTML documents.

EBNF Parser Details

Statistics & Random Numbers

Statistical functions and enhanced random number generation.

stats - Basic descriptive statistics:

func Mean[F ~float64](values []F) F
func Median[F ~float64](values []F) F
func MeanAndStdDev[F ~float64](values []F) (F, F)
func Quantiles[F, Q ~float64](values []F, quantiles ...Q) []F

The stats package provides common statistical functions suitable for high-school level statistics. Functions handle special cases like NaN, Inf, and -Inf appropriately.

rand (deprecated) - Enhanced random number generation:

type Rand struct { /* ... */ }

func New(src Source) *Rand

// Random number generation
func (r *Rand) Int() int
func (r *Rand) Int63() int64
func (r *Rand) Intn(n int) int
func (r *Rand) Float64() float64
func (r *Rand) Perm(n int) []int
func (r *Rand) Shuffle(n int, swap func(i, j int))

// Statistical distributions
func (r *Rand) NormFloat64() float64
func (r *Rand) ExpFloat64() float64

// Sources
type Source interface {
    Uint64() uint64
    Seed(seed uint64)
}

func NewSource(seed uint64) Source

type PCGSource struct { /* ... */ }

Note: The rand package is deprecated. Use math/rand/v2 instead.

Statistics Details Random Number Generation

String Utilities

Efficient string manipulation with UTF-8 rune indexing.

utf8string - Efficient rune-based string indexing:

type String struct { /* ... */ }

func NewString(s string) *String

func (s *String) At(i int) rune
func (s *String) Slice(start, end int) string
func (s *String) String() string

The utf8string package provides efficient indexing of strings by rune position rather than byte position, useful when working with Unicode text.

UTF-8 String Utilities

Module & Version Management

Command-line tools for managing Go modules and dependencies.

gorelease - Semantic version checking tool:

The gorelease command helps module authors validate versions before release by checking API changes against semantic versioning rules. It compares the current module state with a base version and suggests appropriate version numbers.

Usage:

# Compare with latest and suggest new version
gorelease

# Compare with specific version
gorelease -base=v1.2.3

# Check if proposed version is valid
gorelease -base=v1.2.3 -version=v1.3.0

modgraphviz - Module dependency visualization:

Converts go mod graph output to Graphviz DOT format for visualizing module dependencies.

Usage:

go mod graph | modgraphviz | dot -Tpng -o graph.png

txtar - Text-based file archive tool:

Creates and extracts text-based file archives useful for tests and examples.

Usage:

# Create archive
txtar *.go <README >testdata/example.txt

# Extract archive
txtar --extract <archive.txt

txtar Documentation

Gorelease Tool Module Graph Visualization

Module Checksum Database

Tools for working with Go's module checksum database system for module verification.

sumdb - Go module sum database verification:

The sumdb package provides utilities and tools for validating go.sum files against a go.sum database server. It includes internal components for handling signed notes, tamper-evident logs, and transparent key-value storage for module verification.

Sum Database Tools

Type Parameters Utilities

Tools for working with generic Go code and type parameters introduced in Go 1.18.

typeparams - Common utilities for generic code:

The typeparams package provides proxy APIs for new type parameter features in the standard library, along with supplemental utilities for working with generic constructs. It's primarily used by tools that need to interact with generic Go code.

Type Parameters

GUI Framework (Shiny)

Experimental portable GUI framework (separate module).

shiny - Portable GUI framework:

The shiny package provides an experimental GUI framework with support for windows, screens, events, and drawing. It includes drivers for various platforms and OpenGL integration.

Note: This is a separate experimental module focused on GUI development. It includes packages for:

  • Window and screen management
  • Event handling (mouse, keyboard, touch)
  • Drawing and graphics
  • OpenGL integration
  • Platform-specific drivers

GUI Framework Details