typeconv

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 6 Imported by: 0

README

go-typeconv

CI Go Reference License

Safe type conversion utilities for Go. Handle interface{} values from JSON, configs, and APIs

Installation

go get github.com/philiprehberger/go-typeconv

Usage

Type Conversions
import "github.com/philiprehberger/go-typeconv"

// Working with JSON-decoded data
data := map[string]any{
    "port":    8080.0,
    "debug":   "true",
    "timeout": "30s",
}

port, err := typeconv.ToInt(data["port"])       // 8080, nil
debug, err := typeconv.ToBool(data["debug"])    // true, nil
timeout, err := typeconv.ToDuration(data["timeout"]) // 30s, nil
Pointer Helpers
// Create pointers to literals
name := typeconv.Ptr("Alice")   // *string

// Safe dereference with fallback
val := typeconv.Deref(name, "unknown")   // "Alice"
val = typeconv.Deref((*string)(nil), "unknown") // "unknown"

// Safe dereference with zero value
val = typeconv.DerefOrZero((*string)(nil)) // ""
Slice Conversions
// Convert mixed slices from JSON to typed slices
ids, err := typeconv.ToIntSlice([]any{1, "2", 3.0})     // [1, 2, 3], nil
prices, err := typeconv.ToFloat64Slice([]string{"1.5", "2.5"}) // [1.5, 2.5], nil

// Also accepts []int, []float64, []int64, []string directly
vals, err := typeconv.ToIntSlice([]float64{10.0, 20.0})  // [10, 20], nil
Time Parsing
// Parse from RFC3339, date, or datetime strings
t1, err := typeconv.ToTime("2024-06-15T10:30:00Z")    // RFC3339
t2, err := typeconv.ToTime("2024-06-15")               // date only
t3, err := typeconv.ToTime("2024-06-15 10:30:00")      // datetime

// From Unix timestamp (seconds)
t4, err := typeconv.ToTime(int64(1718444400))

// Pass through time.Time
t5, err := typeconv.ToTime(time.Now())
Struct to Map
type User struct {
    Name  string
    Age   int
}

m, err := typeconv.ToMap(User{Name: "Alice", Age: 30})
// map[string]any{"Name": "Alice", "Age": 30}

// Also accepts map[string]any (pass through) and struct pointers
Must Variants
// When you know the conversion will succeed
port := typeconv.MustInt("8080") // 8080
t := typeconv.MustTime("2024-06-15T10:30:00Z")
ids := typeconv.MustIntSlice([]any{1, 2, 3})
// Panics on failure — use only when input is trusted

API

Function Description
ToInt(v any) (int, error) Convert to int from int/float/string/bool
ToInt64(v any) (int64, error) Convert to int64
ToFloat64(v any) (float64, error) Convert to float64 from numeric/string
ToString(v any) (string, error) Convert to string from string/[]byte/Stringer/numeric
ToBool(v any) (bool, error) Convert to bool from bool/string/int
ToDuration(v any) (time.Duration, error) Convert to Duration from Duration/string/int64
ToStringSlice(v any) ([]string, error) Convert to []string from []string/[]any
ToIntSlice(v any) ([]int, error) Convert to []int from []int/[]any/[]string/[]float64/[]int64
ToFloat64Slice(v any) ([]float64, error) Convert to []float64 from []float64/[]any/[]string/[]int/[]int64
ToTime(v any) (time.Time, error) Convert to time.Time from string/int64/time.Time
ToMap(v any) (map[string]any, error) Convert struct or map[string]any to map[string]any
MustInt(v any) int ToInt or panic
MustInt64(v any) int64 ToInt64 or panic
MustFloat64(v any) float64 ToFloat64 or panic
MustString(v any) string ToString or panic
MustBool(v any) bool ToBool or panic
MustDuration(v any) time.Duration ToDuration or panic
MustTime(v any) time.Time ToTime or panic
MustIntSlice(v any) []int ToIntSlice or panic
Ptr[T any](v T) *T Return pointer to value
Deref[T any](p *T, fallback T) T Dereference or fallback
DerefOrZero[T any](p *T) T Dereference or zero value

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package typeconv provides safe type conversion utilities for Go.

It handles interface{} values commonly encountered when working with JSON, configuration files, and external APIs, converting them to concrete Go types with clear error messages for unsupported conversions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Deref

func Deref[T any](p *T, fallback T) T

Deref dereferences a pointer, returning the pointed-to value. If the pointer is nil, it returns the provided fallback value.

func DerefOrZero

func DerefOrZero[T any](p *T) T

DerefOrZero dereferences a pointer, returning the pointed-to value. If the pointer is nil, it returns the zero value for the type.

func MustBool

func MustBool(v any) bool

MustBool converts a value to bool, panicking if the conversion fails.

func MustDuration

func MustDuration(v any) time.Duration

MustDuration converts a value to time.Duration, panicking if the conversion fails.

func MustFloat64

func MustFloat64(v any) float64

MustFloat64 converts a value to float64, panicking if the conversion fails.

func MustInt

func MustInt(v any) int

MustInt converts a value to int, panicking if the conversion fails.

func MustInt64

func MustInt64(v any) int64

MustInt64 converts a value to int64, panicking if the conversion fails.

func MustIntSlice added in v0.2.0

func MustIntSlice(v any) []int

MustIntSlice converts a value to []int, panicking if the conversion fails.

func MustString

func MustString(v any) string

MustString converts a value to string, panicking if the conversion fails.

func MustTime added in v0.2.0

func MustTime(v any) time.Time

MustTime converts a value to time.Time, panicking if the conversion fails.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value. This is useful for creating pointers to literals or inline values.

func ToBool

func ToBool(v any) (bool, error)

ToBool converts a value to bool. Supported source types:

  • bool (pass through)
  • string ("true", "false", "1", "0", "yes", "no" — case insensitive)
  • int, int8, int16, int32, int64 (0=false, nonzero=true)
  • uint, uint8, uint16, uint32, uint64 (0=false, nonzero=true)

func ToDuration

func ToDuration(v any) (time.Duration, error)

ToDuration converts a value to time.Duration. Supported source types:

  • time.Duration (pass through)
  • string (parsed via time.ParseDuration, e.g. "30s", "5m", "1h30m")
  • int64 (interpreted as nanoseconds)

func ToFloat64

func ToFloat64(v any) (float64, error)

ToFloat64 converts a value to float64. Supported source types:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • string (parsed via strconv.ParseFloat)

func ToFloat64Slice added in v0.2.0

func ToFloat64Slice(v any) ([]float64, error)

ToFloat64Slice converts a value to []float64. Supported source types:

  • []float64 (pass through)
  • []any (each element is converted via ToFloat64)
  • []string (each element is parsed via ToFloat64)
  • []int (each element is cast to float64)
  • []int64 (each element is cast to float64)

func ToInt

func ToInt(v any) (int, error)

ToInt converts a value to int. Supported source types:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64 (only if the value has no fractional part)
  • string (parsed via strconv.Atoi)
  • bool (true=1, false=0)

func ToInt64

func ToInt64(v any) (int64, error)

ToInt64 converts a value to int64. Supported source types:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64 (only if the value has no fractional part)
  • string (parsed via strconv.ParseInt)
  • bool (true=1, false=0)

func ToIntSlice added in v0.2.0

func ToIntSlice(v any) ([]int, error)

ToIntSlice converts a value to []int. Supported source types:

  • []int (pass through)
  • []any (each element is converted via ToInt)
  • []string (each element is parsed via ToInt)
  • []float64 (each element is converted via ToInt)
  • []int64 (each element is cast to int)

func ToMap added in v0.2.0

func ToMap(v any) (map[string]any, error)

ToMap converts a value to map[string]any. Supported source types:

  • map[string]any (pass through)
  • struct (exported fields become keys, using field names)

func ToString

func ToString(v any) (string, error)

ToString converts a value to string. Supported source types:

  • string (pass through)
  • []byte
  • fmt.Stringer (calls String())
  • numeric types and bool (via fmt.Sprint)

func ToStringSlice

func ToStringSlice(v any) ([]string, error)

ToStringSlice converts a value to []string. Supported source types:

  • []string (pass through)
  • []any (each element is converted via ToString)

func ToTime added in v0.2.0

func ToTime(v any) (time.Time, error)

ToTime converts a value to time.Time. Supported source types:

  • time.Time (pass through)
  • string (parsed as RFC3339, "2006-01-02", or "2006-01-02 15:04:05")
  • int64 (interpreted as Unix timestamp in seconds)

Types

This section is empty.

Jump to

Keyboard shortcuts

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