Golang 中一个 time.Duration 相关类型转换问题

joyousx · · 2869 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

int (const 和 非const) 转换为 time.Duration

这是一个常见的操作,但是我们会遇到以下代码中的问题,甚是疑惑~

  • 问题

        package main
        import (
            "fmt"
            "reflect"
            "time"
        )
        const a = 1
        func test(a time.Duration) {
            fmt.Printf("%v \n", a)
        }
        func main() {
            b := a + 1
            fmt.Printf("---- a = %v \n", reflect.TypeOf(a))
            test(a)
            fmt.Printf("---- b = %v \n", reflect.TypeOf(b))
            // test(b)  //> 打开注释后, 会编译不通过
        }
    
  • 原因

    Assignability
        A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
            - x's type is identical to T.
            - x's type V and T have identical underlying types and at least one of V or T is not a defined type.
            - T is an interface type and x implements T.
            - x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a defined type.
            - x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
            - x is an untyped constant representable by a value of type T.  
    

就是说,在 const 修饰的变量如果没有明确指明类型时,会根据需要做类型转换; 而非 const 修饰的变量不会。这就可以解释上述代码中的疑惑了。


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:joyousx

查看原文:Golang 中一个 time.Duration 相关类型转换问题

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2869 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传