dongshi3818 2019-01-30 15:21
浏览 87
已采纳

为什么`fmt.Println(“%T ”,e)`中的`e`是错误变量会打印出<nil>而不是其类型?

I was recently playing with the Go language and I bumped into something a bit weird to say the least, let's consider a very simple function:

func main() {
    n, e := fmt.Println(`He said: "Hello"`)
    fmt.Printf("%T
", n)
}

Which outputs what I was expecting:

He said: "Hello"
int

Now if I want to display the type of e:

func main() {
    n, e := fmt.Println(`He said: "Hello"`)
    fmt.Printf("%T
", e)
}

and this time prints out:

He said: "Hello"
<nil>

I get the part that there is no error so e is an empty pointer: nil but I would have not expected to be a ~~type~~ on its own.

Why am I not getting the actual type?

If so, is there a workaround? (not saying my use case is a realistic one but curious if there is any possibility)

  • 写回答

2条回答 默认 最新

  • doufan6886 2019-01-30 15:25
    关注

    The Go Programming Language Specification

    Errors

    The predeclared type error is defined as

    type error interface {
      Error() string
    }
    

    It is the conventional interface for representing an error condition, with the nil value representing no error.

    Interface types

    An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.

    The zero value

    When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: nil for interfaces.


    A zero-value error type, an interface, has no type.Its value is nil.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动