Multiple-value in single-value context

yourbasic.org/golang

Why does this code give a compile error?

t := time.Parse(time.RFC3339, "2018-04-06T10:49:05Z")
fmt.Println(t)
../main.go:9:17: multiple-value time.Parse() in single-value context

Answer

The time.Parse function returns two values, a time.Time and an error, and you must use both.

t, err := time.Parse(time.RFC3339, "2018-04-06T10:49:05Z")
if err != nil {
    // TODO: Handle error.
}
fmt.Println(t)
2018-04-06 10:49:05 +0000 UTC

Blank identifier (underscore)

You can use the blank identifier to ignore unwanted return values.

m := map[string]float64{"pi": 3.1416}
_, exists := m["pi"] // exists == true

Share this page: