i wanna get the value of the largest age from the patients ,
package main
import (
"fmt"
"math"
//"reflect"
)
type patient_details struct {
name string
age int
gender string
}
func main() {
var patient1 = patient_details{"Jack", 22, "male"}
var patient2 = patient_details{"Daniel", 34, "male"}
var patient3 = patient_details{"Sarah", 12, "female"}
var patient4 = patient_details{"Superman", 52, "male"}
fmt.Println("who is the oldest patient in our hospital?")
var oldest_patient = math.Max(patient1.age, patient2.age, patient3.age, patient4.age)
fmt.Println(oldest_patient)
}
i tried max but it only works for 2 float64 vars , so any ideas ??
You can find largest and smallest by sorting age in an array.
package main
import (
"fmt"
"sort"
//"reflect"
)
type patient_details struct {
name string
age int
gender string
}
func main() {
var patient1 = patient_details{"Jack", 22, "male"}
var patient2 = patient_details{"Daniel", 34, "male"}
var patient3 = patient_details{"Sarah", 12, "female"}
var patient4 = patient_details{"Superman", 52, "male"}
fmt.Println("who is the oldest patient in our hospital?")
age := []int{patient1.age,patient2.age,patient3.age,patient4.age}
sort.Ints(age)
fmt.Println("smallest:", age[0], ",Oldest:", age[len(age)-1])
}
age := []int{patient1.age,patient2.age,patient3.age,patient4.age}
this might not be a problem for small arrays but will be a memory waste for big arrays, no need to allocate new array for this problem, just a loop is enough to find max and min as @NobbZ mentioned.