← Library SliceDeterministic

SliceLenOp

Returns the number of elements in a string slice.

Inputs

FieldTypeDescription
Input*[]stringSlice to measure

Outputs

FieldTypeDescription
ResultintNumber of elements

Typical Use Cases

  • Counting classification results
  • Checking how many items a map step produced
  • Routing based on result count

Complete Runnable Example

Counts how many errors were logged during a request so downstream ops can decide whether to escalate.

main.go
package main

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"time"

	"github.com/akennis/sparsi-go/library"
	_ "github.com/akennis/dagor/operator/builtin"

	"github.com/panjf2000/ants/v2"
	"github.com/akennis/dagor"
	"github.com/akennis/dagor/graph"
)

func main() {
	errors := []string{"timeout", "auth_failed", "rate_limit"}
	library.RegisterConst("errors_val", errors)

	g, err := graph.NewBuilder("slicelen_demo").
		Vertex("src").Op("errors_val").Output("Result", "wire_in").
		Vertex("ln").Op("SliceLenOp").
		Input("Input", "wire_in").
		Output("Result", "error_count").
		Build()
	if err != nil {
		log.Fatalf("build: %v", err)
	}

	pool, err := ants.NewPool(4)
	if err != nil {
		log.Fatalf("pool: %v", err)
	}
	defer pool.Release()

	eng, err := dagor.NewEngine(g, pool)
	if err != nil {
		log.Fatalf("engine: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	if err := eng.Run(ctx); err != nil {
		log.Fatalf("run: %v", err)
	}

	out := map[string]any{"errors": errors}
	if raw, ok := eng.GetOutput("error_count"); ok {
		out["error_count"] = *raw.(*int)
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(out)
}