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!

posted @   硅基喵  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示