Go 函数,该函数根据结构的字段返回切片的最小值?

Go 函数,该函数根据结构的字段返回切片的最小值?,go,Go,我有一个Go结构,例如: type patient struct{ patientID int age int bodyTemp int numberVaccines int recordID int } 如何编写一个函数,通过选择我感兴趣的字段来返回患者切片中的最小值 我可以这样称呼它: someSlice := []patient{patient{...},...,...} fmt.Printf("Patient lowest temp: %v",

我有一个Go结构,例如:

type patient struct{
    patientID int
    age int
    bodyTemp int
    numberVaccines int
    recordID int
}
如何编写一个函数,通过选择我感兴趣的字段来返回患者切片中的最小值

我可以这样称呼它:

someSlice := []patient{patient{...},...,...}
fmt.Printf("Patient lowest temp: %v", someSlice.GetMin(bodyTemp)

谢谢

因为它已经写在注释中,所以可以使用反射来完成,但是由于性能下降,没有必要这样做

选择1

至于一个快速解决方案,我建议您实现一个patients 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名患者)的应用程序,正确的方法是向该应用程序引入一个支持索引的存储。

我不明白。最低限度是什么?这里缺少一些重要的东西。你的结构有一个bodyTemp。所以你想得到一个值的最小值?这是你的问题,就像你在这里描述的。对不起,伙计们,我的错。更正了这个问题。你必须在这里进行少量的编程。你正在尝试的可以通过反射来完成,但请不要这样做。它很慢,而且读起来非常困难。正确的方法是每个字段使用一种方法。