Golang 中 error(nil) 为啥 type 也是 unset?

2021-10-20 16:54:04 +08:00
 BBCCBB
m := error(nil)
n := (*error)(nil)
fmt.Printf("%T %+v \n", m, m)
fmt.Printf("%T %+v \n", n, n)

得到的结果

<nil> <nil>
*error <nil>

为啥 m 的 type 是 unset 呢?

1832 次点击
所在节点    程序员
7 条回复
silencil
2021-10-20 16:58:17 +08:00
插个楼,问下 Go 的就业前景如何。以及是否卷?
SingeeKing
2021-10-20 17:06:20 +08:00
error 是接口,%T 打印的是实际类型而不是接口类型,下面的程序 type 就有值了

type Error struct {}
func (e Error) Error() string { return "error" }

var p error = (*Error)(nil)
fmt.Printf("%T %+v \n", p, p)
lipd
2021-10-20 18:06:20 +08:00
@silencil 打开 boss 等招聘 app,选择 golang 就知道了
BBCCBB
2021-10-20 23:06:46 +08:00
@SingeeKing
我的问题其实是从下面这行代码来的.
errorInterface := reflect.TypeOf((*error)(nil)).Elem()

为啥这里 TypeOf 参数用 error(nil)不行... 🐶
joesonw
2021-10-20 23:51:43 +08:00
任意 interface 的 type 都只能这样拿 reflect.Type

interface 是不能实例化的。但*error 是指针类型。
BBCCBB
2021-10-21 09:03:35 +08:00
@joesonw 理是这个理, 但还是懵,哈哈
BBCCBB
2021-10-22 09:07:19 +08:00
这样理解也行, struct can not be nil.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/809274

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX