No, you cannot avoid casting your distance and time back into floats because the division is not defined for those types. And as previously said, Go is strongly typed.
So, in your case you'd have to put casts everywhere (not a good idea). Type aliasing is good if you want to write custom methods for your types, but its purpose is not to solely hide the underlying type under a custom one.
However, not all type are working this way. If you make an alias of a map, then you can call the bracket operators without problem.
type Map map[string]string
func main() {
m := Map(make(map[string]string))
m["answer"] = "42"
fmt.Printf("m's type is %T and answer is %s
", m, m["answer"])
//
// m's type is main.Map and answer is 42
}
Also, when initializing your custom aliases, casting is unnecessary:
type Speed float64
type Distance float64
func main() {
var s Distance = 123.0
var t Time = 300
// ...
}
This compiles and works perfectly. What happens behind the scene is that the literal 123.0
is considered as an untyped float and 300
is considered as an untyped int.
I know this sounds weird but basically those values are not typed so Go tries to fit them into the type at the left. This is why you can write var f float64 = 1
even though 1
is not a float. But you can't write var f float64 = int(1)
because 1 becomes a typed int which cannot be translated in a float64
.
This is why the following won't work:
func main() {
var distance float64 = 123.0
var time float64 = 300
var s Distance = distance
var t Time = time
// ...
}