我可以使类型重定义更优化吗?

I have such code:

type Speed float64
type Distance float64
type Time float64


func speed(a Distance, b Time) Speed {
    return Speed(float64(a) / float64(b))
}

func main() {
    s := Distance(123.0)
    t := Time(300)
    fmt.Println(speed(s, t))
}

Can I make it more optimal by removing somehow casting to float64 in speed function?

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

    // ...
}

You can't make implicit casts between custom types-- Go is strongly typed.

I know this is just a small example, but maybe you really don't need those custom types?

package main

import "fmt"

func speed(distance float64, time float64) float64 {
    return distance / time
}

func main() {
    s := 123.0
    t := 300.0
    fmt.Println(speed(s, t))
}