Skip to content

Instantly share code, notes, and snippets.

@neilchaudhuri
Created March 13, 2019 16:33
Show Gist options
  • Save neilchaudhuri/5f4c9844dbfe1d92fb200c8089c00229 to your computer and use it in GitHub Desktop.
Save neilchaudhuri/5f4c9844dbfe1d92fb200c8089c00229 to your computer and use it in GitHub Desktop.
Idiomatic retrieval of optional values in Go
package main
import "fmt"
type Student struct {
name string
house string
}
func findStudent(key int) (Student, bool) {
students := map[int]Student{1: Student{name: "Harry Potter", house: "Hogwarts"}, 3: Student{name: "Draco Malfoy", house: "Slytherin"}}
student, ok := students[key]
return student, ok
}
func main() {
if student, ok := findStudent(3); ok {
fmt.Printf("The student's name is %v\n", student.name)
} else {
fmt.Println("Back to Hogwarts")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment