douzhouhan4618 2015-12-14 04:30
浏览 260
已采纳

golang中是否有内置的min函数用于切片int参数或可变数量的int参数?

Precursor: I'm just starting to get my feet wet with golang.

This may prove to a be a silly question as it's quite easy to perform these calculations but I'm going to ask it anyway as I didn't find an answer when Googling.

Is there a built in function that returns the minimum of a slice of int arguments:

func MinIntSlice(v []int) (m int) {
    if len(v) > 0 {
        m = v[0]
    }
    for i := 1; i < len(v); i++ {
        if v[i] < m {
            m = v[i]
        }
    }
    return
}

OR the minimum of a variable number of int arguments:

func MinIntVarible(v1 int, vn ...int) (m int) {
    m = v1
    for i := 0; i < len(vn); i++ {
        if vn[i] < m {
            m = vn[i]
        }
    }
    return
}

If not, is the best "convention" simply to create a package that contains helpers like this?

  • 写回答

5条回答 默认 最新

  • duan20081202 2015-12-14 04:47
    关注

    There is no built-in for this.

    If you need this functionality only in one package you can write an un-exported function (e.g. minIntSlice).

    If you need this functionality in multiple packages you can create a package and put similar functions there. You should consider making this package internal (https://golang.org/s/go14internal).

    A few suggestions how to improve your code:

    1. MinIntSlice will return 0 for an empty slice. However 0 is a valid min element as well. I think calling panic on an empty slice is a better option.

    2. Use range loop:

      for i, e := range v {
          if i==0 || e < m {
              m = e
          }
      }
      

    by not giving the index of value it will give you the minimum value 0, which may not be present in given values, so you also have to apply condition on index.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势