gpt4 book ai didi

go - nil 的类型是什么?

转载 作者:行者123 更新时间:2023-12-03 10:09:46 30 4
gpt4 key购买 nike

我想查看 nil在类型开关中。 nil我用什么类型在开关盒中?

 switch v := v.(type) {
case int:
fmt.Println("it's an integer", v)
case ????: <--- what type do I put here?
fmt.Println("it's nil!")
}

最佳答案

I want to check for nil in a type switch. What is the type of nil?


Go 语言规范中没有一个地方指定 nil , 但有多个地方清楚表明 nil没有类型 [ 粗体 强调我的]:
  • section on Variables :

    unless the value is the predeclared identifier nil, which has no type


  • sub-section on Expression switches :

    The predeclared untyped value nil […]



  • 即使 Go 语言规范没有明确说明 nil没有类型,至少应该很明显 nil不可能只有一种类型。至少不是在 Go 中可以表达的类型。 nil是一个有效值
  • 指针,
  • 函数,
  • 接口(interface),
  • slice ,
  • channel 和
  • map 。

  • 这意味着 nil 的类型必须同时是所有这些类型。有几种方法可以实现这一点: nil 的类型可能
  • 所有这些类型的联合类型,
  • 所有这些类型的交集类型(但这不是类型安全的),或
  • 所有这些类型的子类型,或
  • 一种多态类型。

  • 然而,Go 没有联合类型,没有交集类型,没有子类型,也没有多态类型,所以即使 nil有一个类型,这种类型在 Go 中是无法表达的。
    或者,Go 的设计者可以声明 nil没有一种类型,它有多种类型,但这也对您没有帮助:您必须为所有可能的类型提供案例 nil可以,但这些情况不仅仅适用于 nil .您需要为指针提供案例,但该案例将适用于任何指针,而不仅仅是 nil指针等。
    可以检查 nil接口(interface)类型,但是。见 sub-section on Type switches :

    Instead of a type, a case may use the predeclared identifier nil; that case is selected when the expression in the TypeSwitchGuard is a nil interface value. There may be at most one nil case.

    关于go - nil 的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64347531/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com