Top Related Projects
Go library for decoding generic map values into native Go structures and vice versa.
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。
Quick Overview
spf13/cast is a Go library that provides safe and easy casting between different types. It extends Go's built-in type conversion capabilities, offering a more flexible and error-resistant approach to type conversion. The library is particularly useful when dealing with configuration files, JSON data, or any scenario where type conversion is necessary.
Pros
- Simplifies type conversion with a clean and intuitive API
- Provides safe conversions with default values and error handling
- Supports a wide range of data types, including custom types
- Well-maintained and actively developed
Cons
- May introduce a small performance overhead compared to native type assertions
- Requires learning a new API for type conversions
- Some advanced features might be overkill for simple projects
Code Examples
- Basic string to int conversion:
import "github.com/spf13/cast"
str := "123"
num := cast.ToInt(str)
fmt.Println(num) // Output: 123
- Converting to duration with a default value:
import "github.com/spf13/cast"
str := "invalid"
duration := cast.ToDurationE(str).OrDefault(5 * time.Second)
fmt.Println(duration) // Output: 5s
- Converting a map to a struct:
import "github.com/spf13/cast"
type Person struct {
Name string
Age int
}
data := map[string]interface{}{
"Name": "John",
"Age": 30,
}
var person Person
err := cast.MapToStruct(data, &person)
fmt.Printf("%+v\n", person) // Output: {Name:John Age:30}
Getting Started
To use spf13/cast in your Go project, follow these steps:
-
Install the library:
go get github.com/spf13/cast
-
Import the package in your Go code:
import "github.com/spf13/cast"
-
Start using the casting functions:
str := "42" num := cast.ToInt(str) fmt.Printf("Converted %s to %d\n", str, num)
That's it! You can now use the various casting functions provided by the library in your Go code.
Competitor Comparisons
Go library for decoding generic map values into native Go structures and vice versa.
Pros of mapstructure
- More flexible and powerful for complex struct decoding
- Better support for custom decoding logic and hooks
- Handles nested structures and slices more effectively
Cons of mapstructure
- Slightly more complex API, requiring more setup for basic use cases
- Less focus on type conversion, primarily designed for decoding
Code Comparison
mapstructure:
type Person struct {
Name string
Age int
}
var m = map[string]interface{}{"name": "Alice", "age": "30"}
var result Person
mapstructure.Decode(m, &result)
cast:
type Person struct {
Name string
Age int
}
var m = map[string]interface{}{"name": "Alice", "age": "30"}
name := cast.ToString(m["name"])
age := cast.ToInt(m["age"])
Summary
mapstructure excels in complex decoding scenarios, offering more flexibility and power for handling nested structures and custom decoding logic. However, it has a slightly steeper learning curve compared to cast.
cast, on the other hand, focuses on simple type conversions and is more straightforward for basic use cases. It's particularly useful when dealing with individual value conversions rather than full struct decoding.
Choose mapstructure for complex struct decoding tasks, especially when dealing with nested structures or requiring custom decoding logic. Opt for cast when you need quick and easy type conversions for individual values.
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
Pros of validator
- More comprehensive validation functionality, including struct and field validation
- Supports custom validation functions and error messages
- Offers both single field and full struct validation
Cons of validator
- Steeper learning curve due to more complex API
- Requires more setup and configuration for advanced use cases
Code Comparison
validator:
type User struct {
Name string `validate:"required"`
Email string `validate:"required,email"`
Age int `validate:"gte=0,lte=130"`
}
err := validate.Struct(user)
cast:
age := cast.ToInt(ageString)
email := cast.ToString(emailInterface)
Key Differences
- validator focuses on data validation, while cast primarily handles type conversion
- validator operates on structs and fields, cast works with individual values
- validator offers more extensive validation options, cast provides simpler type casting
Use Cases
- Use validator for complex data validation scenarios, especially when working with structs
- Choose cast for straightforward type conversions and basic data manipulation
Community and Maintenance
Both projects are actively maintained and have strong community support. validator has more stars and contributors on GitHub, indicating wider adoption for validation tasks.
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
Pros of govalidator
- Focuses on data validation and sanitization
- Provides a wide range of built-in validation functions
- Supports custom validation rules and error messages
Cons of govalidator
- Limited type conversion capabilities
- Less flexible for general-purpose data manipulation
- May require additional libraries for complex data transformations
Code Comparison
govalidator:
isEmail := govalidator.IsEmail("example@email.com")
sanitized := govalidator.Trim(" hello ", " ")
isURL := govalidator.IsURL("https://example.com")
cast:
age := cast.ToInt("25")
isTrue := cast.ToBool("true")
floatVal := cast.ToFloat64("3.14")
Summary
govalidator excels in data validation and sanitization, offering numerous built-in functions and custom rule support. However, it lacks the extensive type conversion capabilities of cast. On the other hand, cast provides powerful and flexible type conversion functions but doesn't focus on data validation.
Choose govalidator for projects requiring robust input validation and sanitization. Opt for cast when dealing with diverse data types and needing flexible type conversions. For comprehensive data handling, consider using both libraries in conjunction to leverage their respective strengths.
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
Pros of ozzo-validation
- More comprehensive validation framework with built-in rules for various data types
- Supports custom validation rules and error messages
- Allows for struct-level validation in addition to field-level validation
Cons of ozzo-validation
- Steeper learning curve due to more complex API
- Potentially slower performance for simple type conversions
- Requires more setup and configuration for basic use cases
Code Comparison
cast:
age, err := cast.ToInt(ageString)
if err != nil {
// handle error
}
ozzo-validation:
type User struct {
Age int `json:"age"`
}
err := validation.ValidateStruct(&user,
validation.Field(&user.Age, validation.Required, validation.Min(18)),
)
if err != nil {
// handle validation errors
}
Summary
cast is focused on simple type conversions and is easier to use for basic scenarios. ozzo-validation provides a more robust validation framework with extensive options but requires more setup. Choose cast for quick type conversions and ozzo-validation for comprehensive data validation needs.
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、 过滤器,支持自定义验证器、自定义消息、字段翻译。
Pros of validate
- More comprehensive validation features, including built-in rules for common scenarios
- Supports custom validation rules and messages
- Offers both struct tag-based and map-based validation approaches
Cons of validate
- Steeper learning curve due to more complex API
- Less focus on type conversion compared to cast
- May be overkill for simple validation needs
Code comparison
validate:
type User struct {
Name string `validate:"required|minLen:5"`
Email string `validate:"required|email"`
}
v := validate.Struct(user)
if v.Validate() {
fmt.Println("Validation passed")
}
cast:
name := cast.ToString(value)
age := cast.ToInt(value)
isActive := cast.ToBool(value)
Summary
validate is a more feature-rich validation library, offering extensive validation rules and customization options. It's ideal for complex validation scenarios but may be more complex to use.
cast focuses primarily on type conversion and is simpler to use for basic data transformation needs. It lacks built-in validation features but excels in straightforward type casting operations.
Choose validate for comprehensive validation requirements, and cast for simple type conversion tasks.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
cast
Easy and safe casting from one type to another in Go
Donât Panic! ... Cast
What is Cast?
Cast is a library to convert between different go types in a consistent and easy way.
Cast provides simple functions to easily convert a number to a string, an interface into a bool, etc. Cast does this intelligently when an obvious conversion is possible. It doesnât make any attempts to guess what you meant, for example you can only convert a string to an int when it is a string representation of an int such as â8â. Cast was developed for use in Hugo, a website engine which uses YAML, TOML or JSON for meta data.
Why use Cast?
When working with dynamic data in Go you often need to cast or convert the data from one type into another. Cast goes beyond just using type assertion (though it uses that when possible) to provide a very straightforward and convenient library.
If you are working with interfaces to handle things like dynamic content youâll need an easy way to convert an interface into a given type. This is the library for you.
If you are taking in data from YAML, TOML or JSON or other formats which lack full types, then Cast is the library for you.
Usage
Cast provides a handful of To_____ methods. These methods will always return the desired type. If input is provided that will not convert to that type, the 0 or nil value for that type will be returned.
Cast also provides identical methods To_____E. These return the same result as the To_____ methods, plus an additional error which tells you if it successfully converted. Using these methods you can tell the difference between when the input matched the zero value or when the conversion failed and the zero value was returned.
The following examples are merely a sample of what is available. Please review the code for a complete set.
Example âToStringâ:
cast.ToString("mayonegg") // "mayonegg"
cast.ToString(8) // "8"
cast.ToString(8.31) // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil) // ""
var foo interface{} = "one more time"
cast.ToString(foo) // "one more time"
Example âToIntâ:
cast.ToInt(8) // 8
cast.ToInt(8.31) // 8
cast.ToInt("8") // 8
cast.ToInt(true) // 1
cast.ToInt(false) // 0
var eight interface{} = 8
cast.ToInt(eight) // 8
cast.ToInt(nil) // 0
Top Related Projects
Go library for decoding generic map values into native Go structures and vice versa.
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot