Using IsNil() to check for Interface value

When the Interface{} data return shows nil,nil, why s.IsNil() function returns bool value as false when expected is true.
I tried with different non-nil values but the empty interface is a concept I don’t understand.

Below is the code

package main

import "fmt"
import "reflect"

type Auth struct {
    a, b interface{}
}

func main() {
   //p1 := Auth{"test1", "pswd1"}
   // p2 := Auth{123, "pswd2"}
    p1 := Auth{}
    
    callFunc(p1)
}

func callFunc(a ...interface{})  Auth {
  var a1 Auth
  s := reflect.ValueOf(a)
  fmt.Println(a1)

  if (s.IsNil()) {
      fmt.Println("YES")
      fmt.Println(a1)
      a1 = Auth{"NewData", "test2"}
     // return a1
   } else {
      fmt.Println(s.IsNil())
      fmt.Println(s)
      return a1
      
 }
      return a1
}

Output is
false
[{ }]

The expected value is false. The actual value is false.


Package reflect

import “reflect”

func (Value) IsNil

func (v Value) IsNil() bool

IsNil reports whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics. Note that IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value.

func ValueOf

func ValueOf(i interface{}) Value

ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.


type Auth struct {
    a, b interface{}
}

p1 := Auth{}
callFunc(p1)

func callFunc(a ...interface{}) Auth

var a1 Auth

s := reflect.ValueOf(a)

if s.IsNil() {

p1 and a1 are set to the zero value of struct type Auth: {<nil> <nil>}.

s is set to the value of a (from p1), a variadic slice: [{<nil> <nil>}].

s has a value, [{<nil> <nil>}] , it is not nil: s.IsNil() == false.


Your example:

package main

import (
	"fmt"
	"reflect"
)

type Auth struct {
	a, b interface{}
}

func main() {
	//p1 := Auth{"test1", "pswd1"}
	// p2 := Auth{123, "pswd2"}
	p1 := Auth{}

	callFunc(p1)
}

func callFunc(a ...interface{}) Auth {
	var a1 Auth
	s := reflect.ValueOf(a)
	fmt.Println(a1)

	if s.IsNil() {
		fmt.Println("YES")
		fmt.Println(a1)
		a1 = Auth{"NewData", "test2"}
		// return a1
	} else {
		fmt.Println(s.IsNil())
		fmt.Println(s)
		return a1

	}
	return a1
}

https://play.golang.org/p/bgj_QiHNumQ

{<nil> <nil>}
false
[{<nil> <nil>}]

The interface type requires that the actual type and value are both nil to be nil.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.