无界限时通过接口不是零!为什么? (golang) [英] nil slice when passed as interface is not nil! Why? (golang)

查看:77
本文介绍了无界限时通过接口不是零!为什么? (golang)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看这个操场: http://play.golang.org/p/nWHmlw1W01

  package main 

importfmt

func main(){
var i [] int = nil
yes(i)//输出:true
no(i)//输出:false
}

func yes(thing [ ] int){
fmt.Println(thing == nil)
}

func no(thing interface {}){
fmt.Println(thing ==无)
}

为什么两个函数之间的输出差异?

解决方案

不可否认,这有些古怪,但有一个解释。



将一个接口{} 变量想象成一个由两个字段组成的结构:一个是类型,另一个是数据。 ( [] int nil )。实际上,它就像Go运行时一样。

  struct Iface 
{
Itab * tab ;
void * data;
};

当你将nil slice传递给 yes ,只有 nil 作为值传递,所以你的比较归结为 nil == nil

同时,调用 no 会自动将您的变量包装在界面{}中。 c $ c> type并且调用变得类似于 no(interface {[] int,nil})。因此, no 中的比较可以看作是 interface {[] int,nil} == nil ,在旅途中是错误的。



这个问题实际上在 Go FAQ


See this playground: http://play.golang.org/p/nWHmlw1W01

package main

import "fmt"

func main() {
    var i []int = nil
    yes(i) // output: true
    no(i)  // output: false
}

func yes(thing []int) {
    fmt.Println(thing == nil)
}

func no(thing interface{}) {
    fmt.Println(thing == nil)
}

Why the difference in output between the two functions?

解决方案

Admittedly, it's somewhat of a quirk, but there's an explanation for it.

Imagine an interface{} variable as a struct composed of two fields: one is the type and another is the data. ([]int and nil). Actually, it looks just like that in the Go runtime.

struct Iface                                                                                                                   
{                                                                                                                              
    Itab*   tab;                                                                                                               
    void*   data;                                                                                                              
};   

When you pass your nil slice to yes, only nil is passed as the value, so your comparison boils down to nil == nil.

Meanwhile, calling no automatically wraps your variable in an interface{} type and the call becomes something akin to no(interface{[]int, nil}). So the comparison in no could be seen as interface{[]int, nil} == nil, which turns out to be false in go.

The issue is actually explained in the Go FAQ.

这篇关于无界限时通过接口不是零!为什么? (golang)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆