k1t — A Simple Toolkit for Casting, Reflection, and Everyday Go Utilities.
k1 is a Go utility library that provides helper functions for type casting, reflection, and other common programming tasks. It's designed to make your code more concise and readable, especially in testing scenarios.
go get github.com/amberpixels/k1The cast package provides functions for converting between different types:
AsString: Convert a value to a stringAsBytes: Convert a value to a byte sliceAsBool: Convert a value to a booleanAsInt: Convert a value to an integerAsFloat: Convert a value to a floatAsKind: Convert a value to a reflect.KindAsSliceOfAny: Convert a value to a slice of anyAsStrings: Convert a value to a slice of stringsAsTime: Convert a value to a time.Time
The cast package also provides functions for checking if a value is of a certain type:
IsString: Check if a value is a string (with configurable options)IsStringish: Check if a value is string-likeIsNil: Check if a value is nilIsInt: Check if a value is an integerIsStrings: Check if a value is a slice of stringsIsTime: Check if a value is a time.Time
The reflectish package provides helper functions for working with reflection:
IndirectDeep: Recursively dereference pointersLengthOf: Get the length of various types (maps, arrays, strings, channels, slices)
import "github.com/amberpixels/k1/cast"
// Convert a byte slice to a string
str = cast.AsString([]byte("byte_data")) // "byte_data"
// Convert a custom string type
type CustomString string
str = cast.AsString(CustomString("example")) // "example"
// Convert an integer
num := cast.AsInt(42) // "42"
// Convert a float
f := cast.AsFloat(3.14) // "3.14"import "github.com/amberpixels/k1/cast"
// Check if a value is a string
if cast.IsString("example") {
// It's a string
}
// Check if a value is string-like (string, []byte, etc.)
if cast.IsStringish([]byte("example")) {
// It's string-like
}
// Check if a value is nil
if cast.IsNil(someValue) {
// It's nil
}import (
"reflect"
"github.com/amberpixels/k1/reflect"
)
// Recursively dereference pointers
v := reflect.ValueOf(&someValue)
v = reflectish.IndirectDeep(v)
// Get the length of a value
length, ok := reflectish.LengthOf(someValue)
if ok {
// Length is available
}Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.