go - 基于结构字段返回 slice 最小值的函数?

标签 go

我有一个 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/

相关文章:

qt - Golang与Qt在paintEvent中的绘画问题

Go:改造 channel

http - 读取缓冲区并将其重写为 Go 中的 http.Response

json - 将响应数据处理到Struc中

file-io - Go ioutil 使用太多文件描述符/泄漏?

go - 如何获取类型的字符串表示形式?

转到 "unrecognized imports"

arrays - 在go错误中使用 slice 和数组

google-app-engine - Google App Engine 错误中的 LookupHost

elasticsearch - 带 tcp 的 Logstash,错误 :java. io.IOException:连接由对等方重置