Idiomatic Type Conversion in Go

For example,

package main

import "fmt"

func CeilUint(a, b uint64) uint64 {
    return (a + (b - 1)) / b
}

func main() {
    const Width = 64
    var index uint32 = 100
    var bits uint8 = 3
    var c uint64 = CeilUint(uint64(index)*uint64(bits), Width)
    fmt.Println("Test:", c)
}

Output:

Test: 5

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.

Tags:

Go