当前位置: 首页 > article >正文

Go 语言的数据类型转换有哪些?

当不同的数据类型相互操作的时候,就需要类型转换,Go 的数据类型转换还是比较简单的。

数据类型转换包含显式和隐式两类,隐式的一般是小的数据类型到大的类型进行转换,不会有精度丢失的问题。否则就需要进行显式转换。

转换的场景包括:有数学计算、赋值、函数调用、数据库交互、JSON 编解码和接口类型转换。

下面是各个场景的一些代码示例:

1、数学计算

func TestArithmeticOperations(t *testing.T) {
    var length int = 10
    var Width float32 = 5.5
    result := float32(length) * Width
    t.Logf("Result: %f\n", result)
}

2、赋值

func TestAssignValue(t *testing.T) {
    var a int = 10
    result := strconv.Itoa(a)
    t.Logf("Result: %s\n", result)
}

3、函数调用

func processFloat64(f float64) {
    // do something with f
}

func TestFunctionCall(t *testing.T) {
    var input int = 10
    processFloat64(float64(input))
}

4、数据库交互

var quantity int = 10
var price float64 = 24.99

// Database query expecting quantity as float64
db.Query("INSERT INTO products (quantity, price) VALUES (?, ?)", float64(quantity), price)

5、JSON 编码和解码

type Person struct {
    Name string `json:"name"`
}
func TestEncodingAndDecoding(t *testing.T) {
    person := Person{
        Name: "John",
    }
    // Encode the person struct to JSON
    jsonData, err := json.Marshal(person)
    if err != nil {
        t.Errorf("Error encoding person struct to JSON: %v", err)
    }
    t.Logf("JSON data: %s", jsonData)
    
    // Decode the JSON data back to a person struct
    var decodedPerson Person
    err = json.Unmarshal(jsonData, &decodedPerson)
    if err != nil {
        t.Errorf("Error decoding JSON data to person struct: %v", err)
    }
    t.Logf("Decoded person name: %v", decodedPerson.Name)
}

6、接口类型转换

将自定义类型转换为接口

type Share interface {
	Area() float64
}

type Rectangle struct {
	Width  float64
	Height float64
}

type Circle struct {
	Radius float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func (c Circle) Area() float64 {
	return 3.14159 * c.Radius * c.Radius
}
func TestInterfaceConversion(t *testing.T) {
	r := Rectangle{Width: 10, Height: 5}
	c := Circle{Radius: 3}
	s := []Share{r, c}
	for _, item := range s {
		area := item.Area()
		t.Logf("Area: %f\n", area)
	}
}

Over!


http://www.kler.cn/news/361526.html

相关文章:

  • golang正则表达式的使用及举例
  • 搭建微信AI机器人
  • linux介绍与基本指令
  • FineReport 数据筛选过滤
  • 基于SpringBoot+Vue+uniapp微信小程序的教学质量评价系统的详细设计和实现
  • 浏览器控制的无线开关
  • Gee引擎配置微端后登录游戏黑屏怎么办?
  • GEE传奇服务端中自定义颜色文字发送脚本教程
  • 51单片机记录
  • linux-xshell 云服务器的登陆
  • 单片机中断概念以及示例
  • Vue 字符串常用方法
  • 未来的梦想
  • 大数据-184 Elasticsearch - 原理剖析 - DocValues 机制原理 压缩与禁用
  • sql-labs靶场第十八关测试报告
  • SpringCloud无介绍快使用,单机Eureka服务注册中心cloud-eureka-server7001搭建(十)
  • 深入解析TableRAG:突破大规模表格检索的瓶颈
  • ECharts饼图-饼图纹理,附视频讲解与代码下载
  • C++左值和右值
  • C# 里接口(Interface)应用说明
  • 服务器文件夹挂载到客户端
  • 修复Oracle MySQL Server 安全漏洞(CVE-2023-0464)
  • Vue3 学习笔记(三)Vue3 项目打包及目录结构说明
  • TCP传输机制探索:滑动窗口,流量控制、拥塞管理、快重传、延迟应答详解
  • 【汇编语言】第一个程序(一)—— 一个源程序从写出到执行的过程
  • C# Linq常用方法