Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

go-conv

> 编程语言
Open source

Fast conversions across various Go types with a simple API.

382 stars0 likes1 views
WebsiteGitHub

About

Fast conversions across various Go types with a simple API.

Go Package: conv

Get:

bash
go get -u github.com/cstockton/go-conv

Example:

go
// Basic types
if got, err := conv.Bool(`TRUE`); err == nil {
	fmt.Printf("conv.Bool(`TRUE`)\n  -> %v\n", got)
}
if got, err := conv.Duration(`1m2s`); err == nil {
	fmt.Printf("conv.Duration(`1m2s`)\n  -> %v\n", got)
}
var date time.Time
err := conv.Infer(&date, `Sat Mar 7 11:06:39 PST 2015`)
fmt.Printf("conv.Infer(&date, `Sat Mar 7 11:06:39 PST 2015`)\n  -> %v\n", got)

Output:

go
conv.Bool(`TRUE`)
  -> true
conv.Duration(`1m2s`)
  -> 1m2s
conv.Infer(&date, `Sat Mar 7 11:06:39 PST 2015`)
  -> 2015-03-07 11:06:39 +0000 PST

Intro

Notice: If you begin getting compilation errors use the v1 import path gopkg.in/cstockton/go-conv.v1 for an immediate fix and to future-proof.

Package conv provides fast and intuitive conversions across Go types. This library uses reflection to be robust but will bypass it for common conversions, for example string conversion to any type will never use reflection. All functions are safe for concurrent use by multiple Goroutines.

Overview

All conversion functions accept any type of value for conversion, if unable to find a reasonable conversion path they will return the target types zero value and an error.

Example:

…

Output:

go
0 cannot convert "Foo" (type string) to int
42 
42 
42 

Bool

Bool conversion supports all the paths provided by the standard libraries strconv.ParseBool when converting from a string, all other conversions are simply true when not the types zero value. As a special case zero length map and slice types are also false, even if initialized.

Example:

…

Output:

go
true 
false 
true 
false 
true 
false 
true 
false 
true 
false 
false cannot convert struct { string }{string:""} (type struct { string }) to bool

Duration

Duration conversion supports all the paths provided by the standard libraries time.ParseDuration when converting from strings, with a couple enhancements outlined below.

Example:

…

Output:

go
1h1m0.1s 
1h1m0.1s 
1h1m0.1s 
1h1m0.1s 
1h1m0.1s 
1h1m0.1s 
1ns 
1ns 

Float64

Float64 conversion from other float values of an identical type will be returned without modification. Float64 from other types follow the general numeric rules.

Example:

go
fmt.Println(conv.Float64(float64(123.456))) // 123.456
fmt.Println(conv.Float64("-123.456"))       // -123.456
fmt.Println(conv.Float64("1.7976931348623157e+308"))

Output:

go
123.456 
-123.456 
1.7976931348623157e+308 

Infer

Infer will perform conversion by inferring the conversion operation from a pointer to a supported T of the into param. Since the value is assigned directly only a error value is returned, meaning no type assertions needed.

Example:

go
// Infer requires a pointer to all types.
var into int
if err := conv.Infer(into, `42`); err != nil {
	fmt.Println(err)
}
if err := conv.Infer(&into, `42`); err == nil {
	fmt.Println(into)
}

// Same as above but using new()
truth := new(bool)
if err := conv.Infer(truth, `TRUE`); err != nil {
	fmt.Println("Failed!")

Output:

go
cannot infer conversion for unchangeable 0 (type int)
42

Int

Int conversions follow the the general numeric rules.

Example:

go
fmt.Println(conv.Uint("123.456"))               // 123
fmt.Println(conv.Uint("-123.456"))              // 0
fmt.Println(conv.Uint8(uint64(math.MaxUint64))) // 255

Output:

go
123 
0 
255 

String

String conversion from any values outside the cases below will simply be the result of calling fmt.Sprintf("%v", value), meaning it can not fail. An error is still provided and you should check it to be future proof.

Example:

go
// String conversion from other string values will be returned without
// modification.
fmt.Println(conv.String("Foo"))

// As a special case []byte will also be returned after a Go string conversion
// is applied.
fmt.Println(conv.String([]byte("Foo")))

// String conversion from types that do not have a valid conversion path will
// still have sane string conversion for troubleshooting.
fmt.Println(conv.String(struct{ msg string }{"Foo"}))

Output:

go
Foo 
Foo 
{Foo} 

Time

Time conversion from other time values will be returned without modification.

Example:

…

Output:

go
Times:
2006-01-02 15:04:05 +0000 UTC 
Strings:
2006-01-02 15:04:05 +0000 UTC  2006-01-02 15:04:05 +0000 UTC  2006-01-02 15:04:05 +0000 UTC  2006-01-02 15:04:05 +0000 UTC  2006-01-02 15:04:00 +0000 UTC  2006-01-02 15:04:05 +0000 UTC  2006-01-02 15:04:05 +0000 UTC  Errors:
0001-01-01 00:00:00 +0000 UTC cannot convert 1 (type int) to time.Time
0001-01-01 00:00:00 +0000 UTC cannot convert true (type bool) to time.Time

Uint

Uint conversions follow the the general numeric rules.

Example:

go
fmt.Println(conv.Uint("123.456"))               // 123
fmt.Println(conv.Uint("-123.456"))              // 0
fmt.Println(conv.Uint8(uint64(math.MaxUint64))) // 255

Output:

go
123 
0 
255 

Numerics

Numeric conversion from other numeric values of an identical type will be returned without modification. Numeric conversions deviate slightly from Go when dealing with under/over flow. When performing a conversion operation that would overflow, we instead assign the maximum value for the target type. Similarly, conversions that would underflow are assigned the minimun value for that type, meaning unsigned integers are given zero values instead of spilling into large positive integers.

Example:

go
// For more natural Float -> Integer when the underlying value is a string.
// Conversion functions will always try to parse the value as the target type
// first. If parsing fails float parsing with truncation will be attempted.
fmt.Println(conv.Int("-123.456")) // -123

// This does not apply for unsigned integers if the value is negative. Instead
// performing a more intuitive (to the human) truncation to zero.
fmt.Println(conv.Uint("-123.456")) // 0

Output:

go
-123 
0 

Panics

In short, panics should not occur within this library under any circumstance. This obviously excludes any oddities that may surface when the runtime is not in a healthy state, i.e. uderlying system instability, memory exhaustion. If you are able to create a reproducible panic please file a bug report.

Example:

go
// The zero value for the target type is always returned.
fmt.Println(conv.Bool(nil))
fmt.Println(conv.Bool([][]int{}))
fmt.Println(conv.Bool((chan string)(nil)))
fmt.Println(conv.Bool((*interface{})(nil)))
fmt.Println(conv.Bool((*interface{})(nil)))
fmt.Println(conv.Bool((**interface{})(nil)))

Output:

go
false cannot convert  (type ) to bool
false 
false 
false cannot convert (*interface {})(nil) (type *interface {}) to bool
false cannot convert (*interface {})(nil) (type *interface {}) to bool
false cannot convert (**interface {})(nil) (type **interface {}) to bool

Contributing

Feel free to create issues for bugs, please ensure code coverage remains 100% with any pull requests.

Bugs and Patches

Feel free to report bugs and submit pull requests.

  • bugs:

  • patches:

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Goconvconversionconversion-functionsstrconv

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言