R
R
raiboon2015-01-28 18:30:20
go
raiboon, 2015-01-28 18:30:20

How to check if an object is empty?

A fairly common situation for a scripting language, but it is not clear how to solve it in Go:

var previousDate time.Time
...
date, err := time.Parse(dateLayout, dateStr)
...
if previousDate == nil { // ошибка здесь
    previousDate = date
} else {
    ...
}

Error: cannot convert nil to type time.Time
Not sure why . How to implement a check to see if a variable is initialized or not?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uvelichitel, 2015-01-29
@raiboon

In the general case, everything has already been written correctly about initialization, but in the private time.Time you have
if previousDate.IsZero() {

S
Sergey Lerg, 2015-01-28
@Lerg

In Go, all variables are initialized, so the time is not nil/null, but zero - 0 hours, 0 minutes, 0 seconds of the first day of our era.
To check for zero, just create another null variable and compare with it
https://play.golang.org/p/veMgZPPowh

package main

import (
  "time"
  "fmt"
)

func main() {
  var previousDate time.Time
  var zeroTime time.Time
  if previousDate == zeroTime {
    fmt.Println("Is Zero")
  }
  fmt.Println(previousDate)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question