# Inputs and Outputs

> USearch for Go

### Arenas

Every output whose length only the call knows, such as matches, rows, products, monoliths and cursor or stream batches, lands in an `Arena` you pass, and the verb answers a view over it without copying.
`NewArena(executor)` places it where that executor computes, decided once, and `NewArena(nil)` makes host pages for the calling goroutine.
Each call rewinds its arena, so the previous call's views die and a steady loop allocates once.
To keep a result past the next call, or to read one while making the next, pass that call another arena.
An arena serves one call at a time, so each deferred call needs its own.
A stale view answers `StatusUninitialized`; slices an accessor already returned are not checked again.
An arena from a VRAM executor holds device memory, which host accessors refuse with `StatusDevice`.
It grows and frees on that executor's stream, so it serves only calls on that executor, any other finishing `StatusDevice`, and is closed before it; host pages may outlive theirs.

```go
arena, err := usearch.NewArena(executor) // NewArena(nil) makes host pages for the calling goroutine
	if err != nil {
		log.Fatal(err)
}
defer arena.Close()
for _, batch := range batches {
	matches, err := index.On(executor).Search(batch, 10, arena, nil) // rewinds: the last batch's matches are gone
	if err != nil {
		log.Fatal(err)
}
	keys, _, _ := matches.Query(0)
	kept = append(kept, keys...) // a slice into the arena goes stale unchecked, so copy what outlives the loop
}

found, _ := usearch.NewArena(nil) // two live results, two arenas
defer found.Close()
fetched, _ := usearch.NewArena(nil)
defer fetched.Close()
matches, _ := index.Search(query, 10, found, nil)
neighbors, _, _ := matches.Query(0)
for _, key := range neighbors {
	vectors, _ := index.Get(key, usearch.ScalarF32, fetched) // rewinds fetched, never found
	rerank(key, vectors)
}

calls := make([]*usearch.Deferred[usearch.MatchesView], len(shards))
for position, shard := range shards {
	calls[position] = shard.Deferred(executors[position]).Search(queries, 10, arenas[position], nil) // one executor and one arena per submitted call
}
for position, call := range calls {
	if results[position], err = call.Wait(); err != nil {
		log.Fatal(err)
}
}
```

A call that finds its arena serving another call finishes with `StatusContended` and rewinds nothing, so the holder's views stay readable.
`Close` waits for every deferred call naming the arena and retires its views as a rewind does, so a dropped `Deferred` never leaves it unsafe.

### Rows & Scalars

Every verb is a batch over strided matrices, so a memory-mapped dataset reaches the index with no reshape and no copy, and a single vector is a one-row matrix.
A `RowsView` borrows a caller-owned slab as rows of equal width, and it is the shape every batch argument takes.
`RowsOf` derives the row count and the byte pitch from a packed slice; `StridedRowsOf` takes a pitch wider than the row, which is how a memory-mapped dataset with padded rows arrives.

```go
vectors := usearch.RowsOf(embeddings, 768)                    // packed
padded := usearch.StridedRowsOf(mapped, rows, 768, 1024*4)    // pitch of 1024 floats
```

The element type of the slice names the scalar kind, and it is independent of the index's own quantization, since the library converts on ingest and on export.
A `[]float32` query searches a `ScalarI8` index without a conversion pass of your own.

Sub-byte kinds count logical dimensions rather than bytes, so 128 dimensions of `U1x8Scalar` occupy sixteen bytes per row:

```go
packed := make([]usearch.U1x8Scalar, rows*128/8)
vectors := usearch.RowsOf(packed, 128) // 128 dimensions, 16 bytes per row
```

### Search

Every verb with optional knobs ends with a pointer to a config named after its C argument structure, such as `DenseInsertConfig`, `DenseSearchConfig` or `DenseMultiplyConfig`, where `nil` and every zero field derive what the C interface derives.
So `nil` makes the bare call, and naming a field reaches a knob:

```go
var stats usearch.DenseTraversalStats
matches, err := index.On(executor).Search(queries, 10, arena, &usearch.DenseSearchConfig{
	ExpansionFactor: 128,
	Stats:           &stats,
})
fmt.Println(stats.ComputedDistances, "distances computed")
```

A search returns a `MatchesView` over its arena, holding up to `wanted` keys per query and the distances paired with them.
`Query` borrows one query's results, trimmed to the count that query reported, and copies nothing:

```go
for query := range matches.Queries() {
	found, distances, err := matches.Query(query)
	if err != nil {
		log.Fatal(err)
}
	for rank := range found {
		fmt.Println(query, found[rank], distances[rank])
}
}
```

The breadth of the candidates rides each call as `ExpansionFactor` rather than the handle, so a recall sweep runs against one immutable index with no mutation between points.
`Traversal: usearch.TraversalScan` skips the walk and scores every entry exactly, on RAM and NVMe handles, which gives such a sweep its ground truth.

Insertion, refinement and every walk report traversal telemetry when asked.
Each call overwrites the struct rather than accumulating, so a sweep sums them itself:

```go
var stats, total usearch.DenseTraversalStats
for _, batch := range batches {
	if err := index.On(executor).Insert(batch.keys, batch.vectors, &usearch.DenseInsertConfig{Stats: &stats}); err != nil {
		log.Fatal(err)
}
	total.Accumulate(stats)
}
fmt.Println(total.VisitedMembers, total.ComputedDistances, total.Restarts)
```

`import "github.com/unum-cloud/USearch/golang"`

## BFloat16

BFloat16 holds the sixteen bits of a brain floating-point value.

```go
type BFloat16 uint16
```

## DenseInsertConfig

DenseInsertConfig carries the optional settings of Insert.

```go
type DenseInsertConfig struct {
    ExpansionFactor uint
    Progress ProgressCallback
    ProgressSteps uint
    Stats *DenseTraversalStats
}
```

A zero value derives every setting.

- `ExpansionFactor` `uint`: ExpansionFactor is the breadth of the candidates the build walk explores; zero derives it from the geometry.
- `Progress` `ProgressCallback`: Progress reports the entries inserted; every entry is claimed before the first report, so a stop is ignored.
- `ProgressSteps` `uint`: ProgressSteps bounds the reports Progress hears, the last at completion; zero derives to ten.
- `Stats` `*DenseTraversalStats`: Stats is where the traversal telemetry lands, overwritten by the call.

## DenseSearchConfig

DenseSearchConfig carries the optional settings of Search.

```go
type DenseSearchConfig struct {
    ExpansionFactor uint
    Traversal Traversal
    Predicate Predicate
    Progress ProgressCallback
    ProgressSteps uint
    Stats *DenseTraversalStats
}
```

A zero value derives every setting.

- `ExpansionFactor` `uint`: ExpansionFactor is the breadth of the candidates the walk explores; zero derives it from the geometry, and a scan ignores it.
- `Traversal` `Traversal`: Traversal walks the graph by default; TraversalScan scores every entry exactly, on RAM and NVMe handles, and a VRAM handle refuses it with StatusUnsupported.
- `Predicate` `Predicate`: Predicate admits only the keys it approves; nil admits everything. Non-matching entries still route the traversal, so recall does not collapse at low selectivity. A VRAM handle refuses one with StatusDevice.
- `Progress` `ProgressCallback`: Progress reports the queries resolved and stops wherever it says to; a stopped search reports StatusCancelled and returns no matches.
- `ProgressSteps` `uint`: ProgressSteps bounds the reports Progress hears, the last at completion; zero derives to ten.
- `Stats` `*DenseTraversalStats`: Stats is where the traversal telemetry lands, overwritten by the call.

## E2M3Scalar

E2M3Scalar holds the six occupied bits of a two-exponent minifloat.

```go
type E2M3Scalar uint8
```

## E3M2Scalar

E3M2Scalar holds the six occupied bits of a three-exponent minifloat.

```go
type E3M2Scalar uint8
```

## E4M3Scalar

E4M3Scalar holds the eight bits of a four-exponent minifloat.

```go
type E4M3Scalar uint8
```

## E5M2Scalar

E5M2Scalar holds the eight bits of a five-exponent minifloat.

```go
type E5M2Scalar uint8
```

## Element

Element constrains the element types a RowsView may view, ordered by shrinking dynamic range.

```go
type Element interface {
    float64 | float32 | BFloat16 | Float16 |
        E5M2Scalar | E4M3Scalar | E3M2Scalar | E2M3Scalar |
        int8 | I4x2Scalar | uint8 | U4x2Scalar | U1x8Scalar
}
```

## Float16

Float16 holds the sixteen bits of an IEEE half-precision value.

```go
type Float16 uint16
```

## I4x2Scalar

I4x2Scalar holds two 4-bit signed integers.

```go
type I4x2Scalar int8
```

## U1x8Scalar

U1x8Scalar holds eight single-bit dimensions.

```go
type U1x8Scalar uint8
```

## U4x2Scalar

U4x2Scalar holds two 4-bit unsigned integers.

```go
type U4x2Scalar uint8
```

## Arena

Arena is memory the library writes every output whose length scales with a call into - matches, rows, products, monoliths, cursor and stream batches alike - reused so a steady loop allocates once.

```go
type Arena struct {
    // contains filtered or unexported fields
}
```

Every call given an arena rewinds and refills it, so the views of its previous call refuse access
from then on with StatusUninitialized, as they do once it is closed; to keep one call's views
past the next, give that call another arena. An arena serves one call at a time, and a second
overlapping it fails with StatusContended. Deferred verbs borrow it as blocking ones do, since
Close waits for every deferred call naming it. A slice an accessor already handed out is never
checked again, so drop it before the arena's next call.

## NewArena

NewArena makes an empty arena where executor computes, host pages or the memory of its GPU, decided once; a nil executor makes host pages for calls on the calling goroutine.

```go
func NewArena(executor *Executor) (*Arena, error)
```

Nothing is allocated until a call writes into it, and host pages may outlive their executor. A GPU arena grows and frees on its executor's stream, so it serves only calls on that executor, any other or nil finishing StatusDevice, and must be closed before it.

## Close

Close releases the memory, waiting for every deferred call naming the arena, and turns every view over it away.

```go
func (arena *Arena) Close() error
```

It is idempotent, and a closed arena must not be used again.

## Residency

Residency reports where the arena's memory lives.

```go
func (arena *Arena) Residency() Residency
```

A ResidencyVram arena holds device memory, which no Go code may read, so the accessors of its views refuse with StatusDevice.

## DenseTraversalStats

DenseTraversalStats is the traversal telemetry one call reports.

```go
type DenseTraversalStats struct {
    VisitedMembers uint
    ComputedDistances uint
    Restarts uint
    MissingHints uint
}
```

Every call overwrites it rather than accumulating, so a sweep over many batches sums them itself with Accumulate.

- `VisitedMembers` `uint`: VisitedMembers counts the graph members the call visited.
- `ComputedDistances` `uint`: ComputedDistances counts the distances the call computed, diversity re-selections included.
- `Restarts` `uint`: Restarts counts starvation re-seedings - a graph-connectivity health signal rather than a cost counter.
- `MissingHints` `uint`: MissingHints counts hint keys no shard held an entry under; zero unless a search was handed hints.

## Accumulate

Accumulate folds another call's telemetry into this one.

```go
func (stats *DenseTraversalStats) Accumulate(
    other DenseTraversalStats,
)
```

Binding-only.

## MatchesView

MatchesView is a ranked run a call wrote into its arena: per query, up to Columns keys and the scores positionally paired with them.

```go
type MatchesView struct {
    // contains filtered or unexported fields
}
```

A search writes distances, nearest first; a late interaction writes summed similarities, largest first.

## Columns

Columns reports the matches the call made room for per query, at most its wanted - the "k" in "kANN".

```go
func (matches MatchesView) Columns() uint
```

## Queries

Queries reports how many queries the call resolved.

```go
func (matches MatchesView) Queries() uint
```

## Query

Query borrows one query's keys and scores from the arena, trimmed to the count that query reported, and refused with StatusInvalidArgument when query is not below Queries.

```go
func (matches MatchesView) Query(
    query uint,
) ([]Key, []Distance, error)
```

## RowsView

RowsView borrows a caller-owned slab as rows of equal width: a base pointer, a row count, and a byte pitch between consecutive rows.

```go
type RowsView struct {
    // contains filtered or unexported fields
}
```

It is the shape every batch argument takes.

A RowsView borrows and never owns. It stays valid only as long as the slice it was built
from, which the binding pins until each call it crosses is final: the collector traces the
base pointer, so keeping the view alive keeps the backing array alive.

## RowsOf

RowsOf views a packed slab as rows of the given width.

```go
func RowsOf[Value Element](data []Value, dimensions uint) RowsView
```

Panics on a zero width or a partial trailing row: both name a caller's arithmetic mistake
rather than a condition the library could report. Sub-byte kinds count logical dimensions,
so sixteen dimensions of U1x8Scalar occupy two bytes per row.

## StridedRowsOf

StridedRowsOf views a slab whose pitch exceeds its row width - the padded layout a memory-mapped dataset arrives in.

```go
func StridedRowsOf[Value Element](
    data []Value,
    rows, dimensions, stride uint,
) RowsView
```

Panics when the stride cannot hold a row, or when the rows overrun the slab.

## Dimensions

Dimensions reports the logical width of one row.

```go
func (matrix RowsView) Dimensions() uint
```

## Rows

Rows reports how many rows the view spans.

```go
func (matrix RowsView) Rows() uint
```

## Scalar

Scalar reports the scalar type the rows hold.

```go
func (matrix RowsView) Scalar() Scalar
```

## Stride

Stride reports the byte pitch between consecutive row starts.

```go
func (matrix RowsView) Stride() uint
```

## Scalar

Scalar names a stored or exchanged scalar type by width and encoding.

```go
type Scalar int32
```

Sub-byte kinds pack several dimensions per byte, as their xN suffixes spell.

- `ScalarUnknown`: ScalarUnknown tags a type the library could not name.
- `ScalarF64`: ScalarF64 is 64-bit double precision.
- `ScalarF32`: ScalarF32 is 32-bit single precision.
- `ScalarBF16`: ScalarBF16 is the brain floating-point format.
- `ScalarF16`: ScalarF16 is IEEE half precision.
- `ScalarE5M2`: ScalarE5M2 is 8-bit floating point with five exponent bits.
- `ScalarE4M3`: ScalarE4M3 is 8-bit floating point with four exponent bits.
- `ScalarE3M2`: ScalarE3M2 is 6-bit floating point with three exponent bits.
- `ScalarE2M3`: ScalarE2M3 is 6-bit floating point with two exponent bits.
- `ScalarI8`: ScalarI8 is an 8-bit signed integer.
- `ScalarI4x2`: ScalarI4x2 packs two 4-bit signed integers per byte.
- `ScalarI32`: ScalarI32 is a 32-bit signed integer, the coordinates of geospatial points.
- `ScalarU8`: ScalarU8 is an 8-bit unsigned integer.
- `ScalarU4x2`: ScalarU4x2 packs two 4-bit unsigned integers per byte.
- `ScalarU1x8`: ScalarU1x8 packs eight single-bit dimensions per byte.

## String

String renders the scalar kind as the library spells it.

```go
func (scalar Scalar) String() string
```

## Traversal

Traversal is how a search reaches the entries it scores.

```go
type Traversal int32
```

- `TraversalWalk`: TraversalWalk walks the graph, scoring the entries the expansion reaches - approximate, the default.
- `TraversalScan`: TraversalScan scores every entry published when the query's scan starts - exact, on RAM and NVMe handles.

## String

String renders the traversal as the library spells it.

```go
func (traversal Traversal) String() string
```

## DenseValues

DenseValues borrows the rows from their arena as one slab of values, rows end to end, refused with StatusInvalidArgument when Value is not the scalar type they were written as.

```go
func DenseValues[Value Element](
    vectors DenseVectors,
) ([]Value, error)
```

