slicex

package
v0.11.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 9 Imported by: 0

README

SliceX

Type-safe, modern helpers for slice operations and manipulation in Go.

Usage Example

package main

import (
    "fmt"
    "github.com/kaptinlin/gozod/pkg/slicex"
)

func main() {
    // Sample slice
    vals := []int{1, 2, 3}

    // Conversion
    anySlice, _ := slicex.ToAny(vals)         // []any{1,2,3}
    intSlice, _ := slicex.ToTyped[int](anySlice) // []int{1,2,3}
    strSlice, _ := slicex.ToStrings(vals)     // []string{"1","2","3"}

    // Extraction
    if s, ok := slicex.Extract(vals); ok {
        fmt.Println(s) // [1 2 3]
    }

    // Operations
    merged, _ := slicex.Merge([]int{1,2}, []int{3,4}) // [1 2 3 4]
    appended, _ := slicex.Append([]int{1,2}, 3, 4)    // [1 2 3 4]
    reversed, _ := slicex.Reverse([]int{1,2,3})       // [3 2 1]
    unique, _ := slicex.Unique([]int{1,2,2,3})        // [1 2 3]

    // Functional
    evens, _ := slicex.Filter([]int{1,2,3,4}, func(v any) bool {
        return v.(int)%2 == 0
    })
    fmt.Println(evens) // [2 4]
}

Quick Reference

import "github.com/kaptinlin/gozod/pkg/slicex"

// Conversion
slicex.ToAny(slice)           // []any
slicex.ToTyped[T](slice)      // []T
slicex.ToStrings(slice)       // []string
slicex.StringToChars(str)     // []any (chars)

// Extraction
slicex.Extract(val)           // (slice, ok)
slicex.ExtractArray(val)      // (array, ok)
slicex.ExtractSlice(val)      // (slice, ok)

// Operations
slicex.Merge(a, b)            // merge slices
slicex.Append(slice, vals...) // append
slicex.Prepend(slice, vals...)// prepend

// Utility
slicex.Length(slice)          // length
slicex.IsEmpty(slice)         // bool
slicex.Contains(slice, v)     // bool
slicex.IndexOf(slice, v)      // int
slicex.Reverse(slice)         // reversed
slicex.Unique(slice)          // deduped
slicex.Join(slice, sep)       // string

// Functional
slicex.Filter(slice, fn)      // filter
slicex.Map(slice, fn)         // map/transform

Documentation

Overview

Package slicex provides utility functions for working with Go slices.

Key features:

  • Slice conversion (ToAny, ToTyped, ToStrings)
  • Element extraction (Extract, ExtractArray, ExtractSlice)
  • Slice merging (Merge, Append, Prepend)
  • Common utilities (Contains, Unique, Filter, Map, Join)

Usage:

anySlice := slicex.ToAny(typedSlice)
unique := slicex.Unique(slice)
filtered := slicex.Filter(slice, predicate)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidReflectValue = errors.New("invalid reflect value")
	ErrNotCollection       = errors.New("input is not a slice, array, or string")
)

Sentinel errors for input validation.

View Source
var (
	ErrCannotConvert        = errors.New("cannot convert slice")
	ErrCannotConvertElement = errors.New("cannot convert element")
	ErrCannotConvertFirst   = errors.New("cannot convert first slice")
	ErrCannotConvertSecond  = errors.New("cannot convert second slice")
)

Sentinel errors for type conversion.

Functions

func Append

func Append(s any, elements ...any) (any, error)

Append appends elements to a slice, preserving the original slice's concrete type when possible.

func Contains

func Contains(s any, value any) bool

Contains reports whether s contains value, compared using reflect.DeepEqual.

func Extract

func Extract(input any) ([]any, bool)

Extract converts input to []any, returning whether the conversion succeeded.

func ExtractArray

func ExtractArray(input any) ([]any, bool)

ExtractArray extracts an array (not slice) from input. Returns false for nil, slices, or non-array types.

func ExtractSlice

func ExtractSlice(input any) ([]any, bool)

ExtractSlice extracts a slice (not array) from input. Returns false for nil, arrays, or non-slice types.

func Filter

func Filter(s any, fn func(any) bool) (any, error)

Filter returns elements for which fn returns true.

func FromReflect

func FromReflect(rv reflect.Value) ([]any, error)

FromReflect converts a reflect.Value (slice, array, or string) to []any. Returns ErrInvalidReflectValue for invalid values and ErrNotCollection for unsupported kinds.

func IndexOf

func IndexOf(s any, value any) int

IndexOf returns the index of the first occurrence of value in s, or -1 if not found. Comparison uses reflect.DeepEqual.

func IsEmpty

func IsEmpty(input any) bool

IsEmpty reports whether input is nil, empty, or not a recognized collection type.

func Join

func Join(s any, sep string) string

Join formats each element with fmt.Sprintf and joins them with sep. Returns "" for empty or invalid input.

func Length

func Length(input any) (int, error)

Length returns the length of a slice, array, or string. Returns ErrNotCollection for other types.

func Map

func Map(s any, fn func(any) any) (any, error)

Map transforms each element using fn and returns the resulting slice.

func Merge

func Merge(a, b any) (any, error)

Merge concatenates two slices. If both inputs share the same concrete slice type, the result preserves that type. Returns ErrCannotConvertFirst or ErrCannotConvertSecond if the respective input cannot be converted.

func Prepend

func Prepend(s any, elements ...any) (any, error)

Prepend inserts elements before a slice, preserving the original slice's concrete type when possible.

func Reverse

func Reverse(s any) (any, error)

Reverse returns a new slice with elements in reverse order.

func StringToChars

func StringToChars(s string) []any

StringToChars converts a string to []any where each element is a single-character string.

func ToAny

func ToAny(input any) ([]any, error)

ToAny converts a slice, array, or string to []any. A nil input returns (nil, nil). A bare string returns a single-element []any. For unrecognized concrete types, reflection is used as a fallback.

func ToStrings

func ToStrings(input any) ([]string, error)

ToStrings converts any slice to []string by formatting each element with fmt.Sprintf.

func ToTyped

func ToTyped[T any](input any) ([]T, error)

ToTyped converts any slice to []T using generics. Each element is first tried via type assertion, then via reflect conversion. Returns ErrCannotConvertElement if an element cannot be converted to the target type.

func Unique

func Unique(s any) (any, error)

Unique removes duplicate elements, preserving first-occurrence order. Comparable types use a map for O(1) lookup. Non-comparable types use a hash-bucketed approach with structural hashing, falling back to reflect.DeepEqual only on hash collisions.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL