go 类型转换


import (
	"fmt"
	"reflect"
	"strconv"
)

type MyType struct {
	String  string
	Float32 float32
	Float64 float64
	Int     int
	Int64   int64
}

func main() {
	// res := typeto("float64", "3.232")
	// fmt.Printf("this out is %v", res.Float64)
	res := typeto("int", 3.232)
}

func typeto(out string, val interface{}) MyType {
	valType := reflect.TypeOf(val)
	switch valType.Name() {
	case "string":
		return stringTo(val.(string), out)
	case "int":
		return intTo(val.(int), out)
	case "float32":
		return float32To(val.(float32), out)
	case "float64":
		return float64To(val.(float64), out)
	default:
		return MyType{}
	}
	// fmt.Printf("this type is %v", valType.Name())
}

func float64To(val float64, out string) MyType {
	res := MyType{}
	switch out {
	case "int":
		int1 := int(val)
		res = MyType{"", 0, 0, int1, 0}
	case "int64":
		int641 := int64(val)
		res = MyType{"", 0, 0, 0, int641}
	case "float32":
		res = MyType{"", float32(val), 0, 0, 0}
	case "float64":
		res = MyType{"", 0, val, 0, 0}
	case "string":
		str1 := strconv.FormatFloat(val, 'E', -1, 32)
		res = MyType{str1, 0, 0, 0, 0}
	default:
		res = MyType{"", 0, 0, 0, 0}
	}
	return res
}

func float32To(val float32, out string) MyType {
	res := MyType{}
	switch out {
	case "int":
		int1 := int(val)
		res = MyType{"", 0, 0, int1, 0}
	case "int64":
		int641 := int64(val)
		res = MyType{"", 0, 0, 0, int641}
	case "float32":
		res = MyType{"", val, 0, 0, 0}
	case "float64":
		float1 := float64(val)
		res = MyType{"", 0, float1, 0, 0}
	case "string":
		str1 := strconv.FormatFloat(float64(val), 'E', -1, 32)
		res = MyType{str1, 0, 0, 0, 0}
	default:
		res = MyType{"", 0, 0, 0, 0}
	}
	return res
}

func stringTo(val, out string) MyType {
	res := MyType{}
	switch out {
	case "int":
		int1, _ := strconv.Atoi(val)
		fmt.Println("if it is float, that resp is 0")
		res = MyType{"", 0, 0, int1, 0}
	case "int64":
		int64, _ := strconv.ParseInt(val, 10, 64)
		fmt.Println("if it is float, that resp is 0")
		res = MyType{"", 0, 0, 0, int64}
	case "float32":
		float1, _ := strconv.ParseFloat(val, 32)
		res = MyType{val, float32(float1), 0, 0, 0}
	case "float64":
		float, _ := strconv.ParseFloat(val, 64)
		res = MyType{val, 0, float, 0, 0}
	default:
		res = MyType{val, 0, 0, 0, 0}
	}
	return res
}

func intTo(val int, out string) MyType {
	res := MyType{}
	switch out {
	case "string":
		str := strconv.Itoa(val)
		res = MyType{str, 0, 0, 0, 0}
	case "int64":
		int64_ := int64(val)
		res = MyType{"", 0, 0, 0, int64_}
	case "float32":
		float1 := float32(val)
		res = MyType{"", float1, 0, 0, 0}
	case "float64":
		float2 := float64(val)
		res = MyType{"", 0, float2, 0, 0}
	default:
		res = MyType{"", 0, 0, val, 0}
	}
	return res
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值