talira

Easy and safe casting from one type to another in Go

open sourceMITfree

cast is a Go library for converting between types in a consistent way: a number to a string, an interface{} to a bool, a string such as "8" to an int. It converts only when the conversion is obvious and never guesses what you meant. Each To... function returns the zero value when it can't convert, and a matching To...E function also returns an error, so you can tell a failed conversion from a real zero. It suits dynamic data such as values decoded from YAML, TOML or JSON, and was written for Hugo by Steve Francia.

Problems it solves

  • turn an interface{} value from decoded YAML or JSON into a string or int in Go
  • convert config values of unknown type in Go without writing type switches everywhere
  • tell a failed conversion apart from a real zero value

Features

  • To... functions that always return the type asked for (ToString, ToInt and more)
  • To...E variants that return an error alongside the result
  • converts only when the conversion is obvious

Alternatives

The same job

These do what cast does.

  1. swag Helper modules for Go: type conversion, JSON and YAML utilities, name mangling

Compare cast with the top 3