根据struct的字段返回切片的最小值的函数?

问题描述 投票:-6回答:1

我有一个Go结构,例如:

type patient struct{
    patientID int
    age int
    bodyTemp int
    numberVaccines int
    recordID int
}

如何通过选择我感兴趣的字段来编写一个返回patient切片中min值的函数?

我称之为:

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

谢谢!

go
1个回答
0
投票

正如已经在评论中写的那样,您可以使用反射来完成,但由于性能下降,没有必要这样做。

选项1

至于快速解决方案,我建议你实现一个患者切片包装器,它负责按照指定的标准保存和查找所需的数据(对于每个字段都有自己的方法)。这也与性能无关,因为在您的情况下,您需要搜索具有O(N)复杂度的最小值(您需要迭代切片中的所有项)。

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名患者)的应用程序,那么正确的方法是向应用程序引入支持索引的存储。

© www.soinside.com 2019 - 2024. All rights reserved.