I
I
impressive172020-07-20 21:36:59
go
impressive17, 2020-07-20 21:36:59

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

2 answer(s)
E
Evgeny Mamonov, 2020-07-20
@impressive17

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))

complete code

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() == (*S)(nil))
//fmt.Println(InitType() == nil)
}

R
Roman Mirilaczvili, 2020-07-20
@2ord

why is InitType() not compiling at all?
returns the type of the structure, not a pointer to it.
InitPointer() returns true
Go initializes variables, so it's nil for a pointer.
and InitEfaceType() is false
because interface{} is not nil.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question