这段代码的变量声明为什么不会有问题?

6b79 · 2013-10-13 10:26:33 · 3672 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2013-10-13 10:26:33 的主题,其中的信息可能已经有所发展或是发生改变。

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T", t)       // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
} 

来自 Effective Go 里面的代码,不明白那个 t := t.(type) 这里为何不冲突呢。文档解释说,这里重用了这个名字,去重新声明了一个新变量,他们名字相同但是类型不同。还可以这样用?或者是仅仅在 类型 switch 才可以这样。


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

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

3672 次点击  
加入收藏 微博
1 回复  |  直到 2013-10-13 22:26:44
polaris
polaris · #1 · 11年之前

t.(type) 只能在 switch 中使用的类型断言语法

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