我有一个 Go 结构,例如:
type patient struct{
patientID int
age int
bodyTemp int
numberVaccines int
recordID int
}
如何编写一个函数,通过选择我感兴趣的字段返回 patient
slice 中的最小值?
我会这样调用它:
someSlice := []patient{patient{...},...,...}
fmt.Printf("Patient lowest temp: %v", someSlice.GetMin(bodyTemp)
谢谢!
最佳答案
因为已经写在评论中,你可以使用反射来完成,但由于性能下降,没有必要这样做。
选项 1
至于一个快速的解决方案,我建议您实现一个患者 slice 包装器,它负责根据指定的标准(每个字段都有自己的方法)保存和查找您需要的数据。这也与性能无关,因为在您的情况下,您需要搜索具有 O(N) 复杂度的最小值(您需要迭代 slice 中的所有项目)。
package main
import (
"errors"
"fmt"
)
var (
ErrPatientsContainerIsEmpty = errors.New("patients container is empty")
)
type Patient struct{
patientID int
age int
bodyTemp int
numberVaccines int
recordID int
}
type PatientsContainer struct {
patients []Patient
}
func NewPatientsContainer() *PatientsContainer {
patients := make([]Patient, 0)
return & PatientsContainer{
patients: patients,
}
}
func (pc *PatientsContainer) Add(p Patient) {
pc.patients = append(pc.patients, p)
}
func (pc *PatientsContainer) WithMinTemp() (*Patient, error) {
if len(pc.patients) == 0 {
return nil, ErrPatientsContainerIsEmpty
}
patientWithMinTemp := &pc.patients[0]
// O(N) complexity!
for i, p := range pc.patients {
if p.bodyTemp < patientWithMinTemp.bodyTemp {
patientWithMinTemp = &pc.patients[i]
}
}
return patientWithMinTemp, nil
}
func main() {
// some patients data for testing
patients := []Patient{
{
recordID: 1,
bodyTemp: 37,
},
{
recordID: 2,
bodyTemp: 36,
},
{
recordID: 3,
bodyTemp: 38,
},
}
pc := NewPatientsContainer()
// Add to container
for _, p := range patients {
pc.Add(p)
}
patientWithMinTemp, err := pc.WithMinTemp()
if err != nil {
// handle an error
panic(err)
}
fmt.Println(patientWithMinTemp.recordID)
}
选项 2
如果我们谈论的是具有大数据集(不是 50 个患者)的应用程序,正确的方法是向应用程序引入支持索引的存储。
关于go - 基于结构字段返回 slice 最小值的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091185/