Golang在int和uint之间进行转换的成本

I'm porting some old C++ code to go which used unsigned integers fairly often. I can understand their use in the C++ to help ensure positive values were only used in certain places.

However I believe there was also some implicit type conversion going on so in the go version I've ended up with code which looks like

Node{IsTerminal: true, TerminalNo: uint(RandPostiveIntUpTo(int(fitnessCases.Terminals)))})

Which seems a little unnecessary. I'm curious, is there much of a (time) cost to this casting, and am I losing any significant safety by switching to use int everywhere?

This code:

package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()
    var test uint = 3
    var tmp int
    for i := 0; i < 1000000000; i++ {
        tmp = int(test)
    }
    // Required by the compiler
    fmt.Print(tmp)
    end := time.Now()
    fmt.Print("Time elapsed: ", end.Sub(start))
}

Shows how inexpensive it is. Millions of conversions done in less than 3 msecs (my computer is a fairly powerful iMac but you get the point) which is probably mostly going into the iteration cycle rather than the cast.

However, I would encourage you to use ints and play with your logic to ensure the values are correct (e.g. input validation which needs to be done for security reasons anyway).

In C/C++ the type casting was automagic so you did not need to worry to cast between int and uint even though it was happening. In golang, you need to make it explicit but you are in the exact same situation but adding syntax problems.