8. golang 基本类型转换

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

golang 类型转换只能显性转换 不能自动转换

基本数据类型间的转换

	var x1 int = 2
var x2 int16
var x3 int8 x2 = 200 + x1
x3 = 200 + x1

.\test.go:3:8: imported and not used: "fmt"

.\test.go:21:5: cannot use 200 + x1 (type int) as type int16 in assignment

.\test.go:22:5: cannot use 200 + x1 (type int) as type int8 in assignment


	var x1 int = 2
	var x2 int16
	var x3 int8

	x2 = 200 + int16(x1)
	x3 = 200 + int8(x1)

.\test.go:22:11: constant 200 overflows int8

基本数据类型和 string 之间的转换

1. 使用 fmt.sprintf 函数进行

package main

import "fmt"

func main() {
var x1 int = 88
var x2 float32 = 3.45
var x3 string x3 = fmt.Sprintf("this is a int %d \n", x1) //注意一定要使用双引号
fmt.Print(x3)
x3 = fmt.Sprintf("this is a float str %f \n", x2)
fmt.Print(x3)
}

2. 使用 strconv 函数

package main

import (
"fmt"
"strconv"
) func main() {
var xx int = 123 s := strconv.FormatInt(int64(xx), 16)
fmt.Print(s) }

字符串string 转换为 基本数据类型

使用strconv 内容

package main

import (
"fmt"
"strconv"
) func main() {
var xx string = "1232123"
xxx, _ := strconv.ParseInt(xx, 10, 32)
fmt.Printf("this xxx is %T %d", xxx, xxx)
// this xxx is int64 1232123 } 只能返回64位 如果需要32位 要自己在进行一次转换 注意事项 字符串强行转换为int 会有以下状况
package main

import (
	"fmt"
	"strconv"
)

func main() {
	var xx string = "hello"
	xxx, _ := strconv.ParseInt(xx, 10, 32)
	fmt.Printf("this xxx is %T  %d", xxx, xxx)
// this xxx is int64  0

}

  

 

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: gogolang