教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang中interface类型转string类型

Golang中interface类型转string类型

发布时间:2023-01-10   编辑:jiaochengji.com
教程集为您提供Golang中interface类型转string类型等资源,欢迎您收藏本站,我们将为您提供最新的Golang中interface类型转string类型资源


【代码】

// Strval 获取变量的字符串值
// 浮点型 3.0将会转换成字符串3, "3"
// 非数值或字符类型的变量将会被转换成JSON格式字符串
func Strval(value interface{}) string {
	var key string
	if value == nil {
		return key
	}

	switch value.(type) {
	case float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		key = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case string:
		key = value.(string)
	case []byte:
		key = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}

	return key
}
到此这篇关于“Golang中interface类型转string类型”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang中[]string转[]interface{}实现
go语言学习-Any类型
goLang 类型断言 type assertion
golang判断变量的类型
2020-10-18Go语言接口
【Golang】go语言面向接口
Golang中对interface{}做type assertion和type switch学习笔记
go interface类型转换_Golang系列5 | Interface接口&map类型
Golang interface赋值与取值的实例
Go语言的空接口,接口类型断言

[关闭]
~ ~