import (
"fmt"
)
type str struct {
a string
}
func main() {
var p *str
chk(p)
}
func chk(s interface{}) {
fmt.Println("Check", s) // HERE IT IS PRINTING NIL
if s == nil { // BUT HERE I AM UNABLE TO CHECK
fmt.Println("It is null....")
}
fmt.Println("Hello, playground")
}
package main
import (
"fmt"
)
type str struct {
a string
}
func main() {
var p *str
chk(p)
}
func chk(s interface{}) {
fmt.Printf("value=%v type=%t\n", s, s)
// The type of s is not nil, so the following is false.
if s == nil {
fmt.Println("It is null....")
}
fmt.Println("Hello, playground")
}
The ouput is
value=<nil> type=%!t(*main.str=<nil>)
Hello, playground
To be nil
, both the type and the value must be nil
.
See also https://u.lhorn.de/mo3Z.
1 Like
Thank you Lutzhorn,
your reply was most useful
and one more thing
How can i check only the value is empty?
Try this:
package main
import (
"fmt"
"reflect"
)
type str struct {
a string
}
func main() {
var p *str
chk(p)
}
func chk(s interface{}) {
fmt.Printf("value=%v type=%t\n", s, s)
// The type of s is not nil, so the following is false.
if s == nil {
fmt.Println("s is nil....")
}
// The value of s is nil, the following is true.
if reflect.ValueOf(s).IsNil() {
fmt.Println("value of s is nil")
}
fmt.Println("Hello, playground")
}
Output:
value=<nil> type=%!t(*main.str=<nil>)
value of s is nil
Hello, playground
See also https://u.lhorn.de/m65w.
1 Like
import (
"fmt"
"reflect"
)
var string1 string
var int1 int
type strtemp struct {
newstr string
}
type str struct {
a string
st *strtemp
}
func main() {
var p *str
chk(string1)
chk(int1)
chk(p)
}
func chk(s interface{}) {
fmt.Printf("value=%v type=%t\n", s, s)
// The type of s is not nil, so the following is false.
if s == nil {
fmt.Println("s is nil....")
}
// The value of s is nil, the following is true.
if reflect.ValueOf(s).IsNil() {
fmt.Println("value of s is nil")
}
fmt.Println("Hello, playground")
}
panic: reflect: call of reflect.Value.IsNil on string Value
goroutine 1 [running]:
reflect.Value.IsNil(0xee6e0, 0x195920, 0x98, 0x195920, 0x98, 0xf0740)
/usr/local/go/src/reflect/value.go:1018 +0x160
main.chk(0xee6e0, 0x195920)
/tmp/sandbox753849162/main.go:33 +0xc0
main.main()
/tmp/sandbox753849162/main.go:21 +0x60```
This is the error i’m facing… i’m trying all type of values
int
and string
can not be used like this. But why do you want to pass them as an interface{}
? What are you trying to do?
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.