Created
March 13, 2019 16:33
-
-
Save neilchaudhuri/5f4c9844dbfe1d92fb200c8089c00229 to your computer and use it in GitHub Desktop.
Idiomatic retrieval of optional values in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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