12

Multiple-value in single-value context

 3 years ago
source link: https://yourbasic.org/golang/gotcha-multiple-value-single-value-context/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Multiple-value in single-value context

yourbasic.org/golang
single-vs-multiple-values.jpg

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:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK