您的位置:首页 > 财经 > 产业 > 湖南省人民政府驻深圳办事处_外贸网站建设费用情况_合肥做网站哪家好_如何设置友情链接

湖南省人民政府驻深圳办事处_外贸网站建设费用情况_合肥做网站哪家好_如何设置友情链接

2025/2/23 10:46:20 来源:https://blog.csdn.net/github_37151951/article/details/143164617  浏览:    关键词:湖南省人民政府驻深圳办事处_外贸网站建设费用情况_合肥做网站哪家好_如何设置友情链接
湖南省人民政府驻深圳办事处_外贸网站建设费用情况_合肥做网站哪家好_如何设置友情链接

当不同的数据类型相互操作的时候,就需要类型转换,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!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com