Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I convert an integer to a float64 to type match?

Tags:

go

I have been playing around with Go and I ran into a (non?)feature of Go while running the following code:

a := 1     //int
b := 1.0   //float64

c := a/b   //should be float64

When I ran this I get the following run-time error:

invalid operation: a / b (mismatched types int and float64) 

I thought GoLang was supposed to be pretty good with type inference. Why should it be necessary for me to write:

c := float64(a)/b    //float64

In general, given two number types, c should be inferred to be the smallest type that contains both. I can't see this as being an oversight, so I am just trying to figure out why this behavior was decided upon. For readability reasons only? Or would my suggested behavior cause some kind of logical inconsistency in language or something?

like image 266
breeden Avatar asked Jul 11 '15 04:07

breeden


People also ask

How to convert float to int in Go?

looks like var y = int(x) is suffice with new GO version.

Does python automatically convert to float?

Integers and floating-point numbers can be mixed in arithmetic. Python 3 automatically converts integers to floats as needed.

How to convert variable to string in Go?

You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.


1 Answers

This is mentioned in the FAQ: Why does Go not provide implicit numeric conversions?

The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?
It also complicates the compiler.

That is why you need:

  • either to do an explicit type conversion:

    c := float64(a)/b
    
  • or to use var float64

    var a, b float64
    a = 1     //float64
    b = 1.0   //float64
    c := a/b 
    
like image 130
VonC Avatar answered Sep 22 '22 13:09

VonC