dongza3124 2016-06-09 14:51
浏览 22
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • douyamitong57935 2016-06-09 15:28
    关注

    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
    
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?