当不同的数据类型相互操作的时候,就需要类型转换,Go 的数据类型转换还是比较简单的。
数据类型转换包含显式和隐式两类,隐式的一般是小的数据类型到大的类型进行转换,不会有精度丢失的问题。否则就需要进行显式转换。
转换的场景包括:有数学计算、赋值、函数调用、数据库交互、JSON 编解码和接口类型转换。
下面是各个场景的一些代码示例:
1、数学计算
func TestArithmeticOperations(t *testing.T) {var length int = 10var Width float32 = 5.5result := float32(length) * Widtht.Logf("Result: %f\n", result)
}
2、赋值
func TestAssignValue(t *testing.T) {var a int = 10result := 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 = 10processFloat64(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 JSONjsonData, 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 structvar decodedPerson Personerr = 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 float64Height 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!