Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/castPublic

safe and easy casting from one type to another in Go

License

NotificationsYou must be signed in to change notification settings

spf13/cast

Repository files navigation

GitHub Workflow StatusPkgGoDevGo VersionGo Report Card

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, aninterface into a bool, etc. Cast does this intelligently when an obviousconversion 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 stringrepresentation of an int such as “8”. Cast was developed for use inHugo, a website engine which uses YAML, TOML or JSONfor meta data.

Why use Cast?

When working with dynamic data in Go you often need to cast or convert the datafrom one type into another. Cast goes beyond just using type assertion (thoughit uses that when possible) to provide a very straightforward and convenientlibrary.

If you are working with interfaces to handle things like dynamic contentyou’ll need an easy way to convert an interface into a given type. Thisis the library for you.

If you are taking in data from YAML, TOML or JSON or other formats which lackfull types, then Cast is the library for you.

Usage

Cast provides a handful of To_____ methods. These methods will always returnthe desired type.If input is provided that will not convert to that type, the0 or nil value for that type will be returned.

Cast also provides identical methods To_____E. These return the same result asthe To_____ methods, plus an additional error which tells you if it successfullyconverted. Using these methods you can tell the difference between when theinput matched the zero value or when the conversion failed and the zero valuewas returned.

The following examples are merely a sample of what is available. Please reviewthe 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)                  // 8cast.ToInt(8.31)               // 8cast.ToInt("8")                // 8cast.ToInt(true)               // 1cast.ToInt(false)              // 0var eight interface{} = 8cast.ToInt(eight)              // 8cast.ToInt(nil)                // 0

[8]ページ先頭

©2009-2025 Movatter.jp