乐闻世界logo
搜索文章和话题

How do you convert between different numeric types in Go?

1个答案

1

In Go, to convert between different numeric types, you must use type conversion. Go does not support implicit type conversion, meaning that even for compatible types, explicit conversion is required. The following are basic methods for converting different numeric types in Go:

Basic Syntax

The basic syntax for conversion in Go is:

go
type_name(expression)

where type_name is the target type, and expression is the value to convert.

Example

Suppose you have an integer (int) and need to convert it to a floating-point type (float64). You can do this:

go
package main import ( "fmt" ) func main() { var myInt int = 42 var myFloat float64 myFloat = float64(myInt) fmt.Println(myFloat) }

This code will output: 42 (now a float64 value).

Conversion Considerations

When performing type conversion, consider the compatibility and range of types. For example, converting from float64 to int truncates the fractional part, retaining only the integer portion. Attempting to convert a value outside the target type's range may cause overflow or unexpected behavior.

Practical Example for Converting Different Types

Suppose you are handling financial data and receive price information as float64 from an API, but your database stores prices as int (in cents to avoid floating-point precision issues). Here is an example of how to handle this conversion:

go
package main import ( "fmt" "math" ) func main() { var priceFromAPI float64 = 99.99 // Convert price from dollars to cents (int type) var priceInCents int = int(math.Round(priceFromAPI * 100)) fmt.Println(priceInCents) // Output: 9999 }

Here, we use the math.Round function to ensure proper rounding to the nearest integer before conversion.

By using these basic methods and considerations, you can effectively perform type conversions in Go, ensuring correct usage of data types and the robustness of your applications.

2024年8月7日 18:19 回复

你的答案