Why would I need to convert an integer to float64 to match the type?
I was playing around with Go and I ran into (not?) The Go function while running the following code:
a := 1 //int b := 1.0 //float64 c := a/b //should be float64
When I run this, I get the following runtime error:
invalid operation: a / b (mismatched types int and float64)
I thought GoLang should be pretty good with the output type. Why do I need to write:
c := float64(a)/b //float64
In general, if two types of numbers are given, c should be inferred as the smallest type that contains both. I don't see this as an oversight, so I'm just trying to understand why this behavior was accepted. For readability only? Or is my suggested behavior causing some kind of logical inconsistency in the language or something else?
source to share
The FAQ states this: Why doesn't Go provide implicit numeric conversions?
The convenience of automatic conversion between numeric types in C is outweighed by the confusion it introduces. When is an unsigned expression? How great is the value? Is it overflow? Is the result portable regardless of the machine it is running on?
It also complicates the compiler.
This is why you need:
-
or make an explicit type conversion :
c := float64(a)/b
-
or use
var float64
var a, b float64 a = 1 //float64 b = 1.0 //float64 c := a/b
source to share