Answer the question
In order to leave comments, you need to log in
Why does one function return true and the other false?
Why does InitPointer() return true but InitEfaceType() returns false, and why doesn't InitType() compile at all?
package main
import (
"fmt"
)
type S struct{}
func (s S) F() {}
func InitPointer() *S {
var s *S
return s
}
func InitEfaceType() interface{} {
var s S
return s
}
func InitType() S {
var s S
return s
}
func main() {
fmt.Println(InitPointer() == nil)
fmt.Println(InitEfaceType() == nil)
//fmt.Println(InitType() == nil)
}
Answer the question
In order to leave comments, you need to log in
Because the InitEfaceType function actually returns a structure, not a pointer.
Structure cannot be nil. If you return a pointer to a structure, then you can already check for nil.
Do fmt.Printf("Type: %T\n", InitEfaceType()) and you will see the type "main.S"
To be able to check the interface for nil you can do like this:
func InitEfaceType() interface{} {
var s *S
return s
}
...
fmt.Println(InitEfaceType() == (*S)(nil))
why is InitType() not compiling at all?returns the type of the structure, not a pointer to it.
InitPointer() returns trueGo initializes variables, so it's nil for a pointer.
and InitEfaceType() is falsebecause interface{} is not nil.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question