golang 基本数据类型和string的相互转换

1、基本类型转 string 类型

1.1、方式一:fmt.Sprintf格式化
package main

import "fmt"

func main() {
	var num1 int = 99
	var num2 float64 = 123.12
	var b bool = true
	var myChar byte = 'h'
	//var str string

	//int 转为 string
	str := fmt.Sprintf("%d", num1)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//float64 转为 string
	str = fmt.Sprintf("%f", num2)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//bool 转为 string
	str = fmt.Sprintf("%t", b)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//byte 转为 string
	str = fmt.Sprintf("%c", myChar)
	fmt.Printf("str type : %T , str=%q
", str, str)
}

// str type : string , str="99"
// str type : string , str="123.120000"
// str type : string , str="true"
// str type : string , str="h"
1.2、方式二:strconv包的函数
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var num1 int = 99
	var num2 float64 = 123.12
	var b bool = true
	var myChar byte = 'h'

	//方式一、int 转为 string
	str := strconv.FormatInt(int64(num1), 10)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//方式二、int 转为 string
	str = strconv.Itoa(num1)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//float64 转为 string
	str = strconv.FormatFloat(num2, 'f', 10, 64)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//bool 转为 string
	str = strconv.FormatBool(b)
	fmt.Printf("str type : %T , str=%q
", str, str)

	//byte 转为 string
	//str = strconv.Itoa(int(myChar))
	str = string(myChar)
	fmt.Printf("str type : %T , str=%q", str, str)
}

// str type : string , str="99"
// str type : string , str="99"
// str type : string , str="123.1200000000"
// str type : string , str="true"
// str type : string , str="h"

2、 string 类型转基本数据类型

2.1、strconv 包的函数
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var num1 string = "99"
	var num2 string = "123.12"
	var b string = "true"

	// string 转为 int64
	str, _ := strconv.ParseInt(num1, 10, 64)
	fmt.Printf("str type: %T str=%d
", str, str)

	// string 转为 float64
	number, _ := strconv.ParseFloat(num2, 64)
	fmt.Printf("str type: %T str=%f
", number, number)

	// string 转为 bool
	ret, _ := strconv.ParseBool(b)
	fmt.Printf("str type: %T str=%t
", ret, ret)
}

// str type: int64 str=99
// str type: float64 str=123.120000
// str type: bool str=true
原文地址:https://www.cnblogs.com/ygbh/p/14153678.html