Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Type Conversion in Go

Tags:

go

I was playing around with Go and was wondering what the best way is to perform idiomatic type conversions in Go. Basically my problem lays within automatic type conversions between uint8, uint64, and float64. From my experience with other languages a multiplication of a uint8 with a uint64 will yield a uint64 value, but not so in go.

Here is an example that I build and I ask if this is the idiomatic way of writing this code or if I'm missing an important language construct.

package main

import ("math";"fmt")

const(Width=64)

func main() {

    var index uint32
    var bits uint8

    index = 100
    bits = 3

    var c uint64
    // This is the line of interest vvvv
    c = uint64(math.Ceil(float64(index * uint32(bits))/float64(Width)))
    fmt.Println("Test: %v\n", c)
}

From my point of view the calculation of the ceiling value seems unnecessary complex because of all the explicit type conversions.

Thanks!

like image 268
grundprinzip Avatar asked Nov 13 '12 20:11

grundprinzip


People also ask

How to convert one type to another type in Golang?

Type conversion is required when you need to convert one variable type into another, usually because a particular variable or function argument requires it. If you want to convert an int64 to an int , the syntax is: x := int(y) , where y is an int64 and x is an int .

What kind of type conversion is supported by Go?

Golang Implicit Type Casting Implicit type conversion, also known as coercion in Golang is an automatic type conversion by the compiler. Golang does not support implicit type conversion because of its robust type system. Some languages allow or even require compilers to provide coercion.

How a variable type is checked at runtime in Go language?

A quick way to check the type of a value in Go is by using the %T verb in conjunction with fmt. Printf . This works well if you want to print the type to the console for debugging purposes.


1 Answers

There are no implicit type conversions for non-constant values.

You can write

var x float64
x = 1

But you cannot write

var x float64
var y int

y = 1
x = y

See the spec for reference.

There's a good reason, to not allow automatic/implicit type conversions, as they can become very messy and one has to learn many rules to circumvent the various caveats that may occur. Take the Integer Conversion Rules in C for example.

like image 193
nemo Avatar answered Oct 23 '22 22:10

nemo