Sobes.tech
Junior — Senior

Determining the program output when working with nil interface and nil pointer

livecode

Task condition

It is necessary to predict what text will be output when running the program, considering the features of comparing interfaces with nil in Go.

type Order interface {
  GetID() int
}

type orderStruct struct {
  ID int
}

func (o *orderStruct) GetID() int {
  return o.ID
}

func createOrder(shouldCreate bool) Order {
  var order *orderStruct
  fmt.Println("in createOrder: ", order == nil)

  if shouldCreate {
    order = &orderStruct{ID: 1}
  }
  return order
}

func main() {
  order1 := createOrder(true)
  if order1 != nil {
    fmt.Printf("Order1 has ID: %d\n", order1.GetID())
  } else {
    fmt.Println("Order1 is nil")
  }

  order2 := createOrder(false)
  if order2 != nil {
    fmt.Printf("Order2 has ID: %d\n", order2.GetID())
  } else {
    fmt.Println("Order2 is nil")
  }
}