// cast.go// ToInt casts an interface to an int type.funcToInt(iinterface{})int{ v, _ := ToIntE(i)returnv }// caste.go// ToIntE casts an interface to an int type.funcToIntE(iinterface{})(int,error) { i = indirect(i)// 这个 indirect 函数里使用反射来获取 i 的 interface{}...
到了第二个 `ToInt`,cast 的优势就更明显了,传统方式下,一个 `interface{}` 类型的 `"123"` 如果要转换成 `int`,必须先类型断言为 `string`,再使用 `strconv` 转换成 `int`,代码就不写了,想象一下就知道有多麻烦,而 cast 可以将这个过程一步到位。 接着是第三个输出 `cast.ToInt(str)`,这里的...
其中,interfaceValue是一个接口类型的值,Type是要转换的具体类型。断言将接口值转换为具体类型,并将转...
阅读cast源码,我们可以发现,cast.ToString()底层实现是调用cast.ToStringE(),只不过是将cast.ToStringE()返回的错误忽略了。 源码: 代码语言:javascript 复制 // ToString casts an interface to a string type.funcToString(iinterface{})string{v,_:=ToStringE(i)returnv} 我们可以使用cast.ToxxxE()函数,判定...
(or nil) or an implementation of fmt.Stringer// or error,funcindirectToStringerOrError(a any)any{ifa==nil{returnnil}v:=reflect.ValueOf(a)for!v.Type().Implements(fmtStringerType)&&!v.Type().Implements(errorType)&&v.Kind()==reflect.Pointer&&!v.IsNil(){v=v.Elem()}returnv.Interface()...
interface{} time.Time time.Duration nil 1. 2. 3. 4. 高级转换 cast提供了两组函数: ToType(其中Type可以为任何支持的类型),将参数转换为Type类型。如果无法转换,返回Type类型的零值或nil; ...
type Animal interface { Speak() string } // 定义一个结构体类型 type Dog struct{} // Dog 结构体类型实现了 Animal 接口的 Speak 方法 func (d Dog) Speak() string { return "Woof!" } // main 函数 func main() { // 创建一个 Dog 对象 ...
func TestCast(t*testing.T){//1. 转字符串fmt.Println(cast.ToString("helloworld"))//helloworldfmt.Println(cast.ToString(66))//"66"fmt.Println(cast.ToString(3.1415926))//"3.1415926"fmt.Println(cast.ToString([]byte("one time")))//"one time"varretinterface{} ="helloWorld"fmt.Println(cast....
type Book struct { Title string Author string } func main() { // Create objects to marshal. book := Book{"The Myth of Sisyphus", "Albert Camus"} box := make(map[string]interface{}) box["The Myth of Sisyphus"] = &book itemType := reflect.TypeOf(box["The Myth of Sisyphus"]) ...
var val interface{} = 314 num, ok := val.(int) if ok { fmt.Printf("value: %d, type: %T\n", num, num) } else { fmt.Println("assertion failed") } } In this example, we create a “val” interface that contains an integer. We then use a type assertion to extract the intege...