← Library SliceDeterministic

SliceFirstOp

Returns the first element of a string slice. Errors if the slice is empty.

Inputs

FieldTypeDescription
Input*[]stringSlice to read from

Outputs

FieldTypeDescription
ResultstringFirst element

Errors on empty slice. Use IfEmptySliceStringOp first if the slice could be empty.

Typical Use Cases

  • Taking the top-ranked result
  • Extracting the first classification label
  • First item from a retrieved candidate set

Complete Runnable Example

Picks the highest-ranked candidate from a list of AI-ranked suggestions.

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() {
	candidates := []string{"Alice", "Bob", "Carol"}
	library.RegisterConst("candidates_val", candidates)

	g, err := graph.NewBuilder("slicefirst_demo").
		Vertex("src").Op("candidates_val").Output("Result", "wire_in").
		Vertex("fst").Op("SliceFirstOp").
		Input("Input", "wire_in").
		Output("Result", "top_pick").
		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{"candidates": candidates}
	if raw, ok := eng.GetOutput("top_pick"); ok {
		out["top_pick"] = *raw.(*string)
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(out)
}