go - Why must I convert an integer to a float64 to type match? -
i have been playing around go , ran (non?)feature of go while running following code:
a := 1 //int b := 1.0 //float64 c := a/b //should float64
when ran following run-time error:
invalid operation: / b (mismatched types int , float64)
i thought golang supposed pretty type inference. why should necessary me write:
c := float64(a)/b //float64
in general, given 2 number types, c should inferred smallest type contains both. can't see being oversight, trying figure out why behavior decided upon. readability reasons only? or suggested behavior cause kind of logical inconsistency in language or something?
this mentioned in faq: why go not provide implicit numeric conversions?
the convenience of automatic conversion between numeric types in c outweighed confusion causes. when expression unsigned? how big value? overflow? result portable, independent of machine on executes?
complicates compiler.
that why need:
either explicit type conversion:
c := float64(a)/b
or use
var float64
var a, b float64 = 1 //float64 b = 1.0 //float64 c := a/b
Comments
Post a Comment