douyinbo3361 2018-05-12 22:35
浏览 2069
已采纳

返回Golang中string.Split()切片的最后一项

I am splitting file names in Go to get at the file extension (e.g. import ("strings") ; strings.Split("example.txt", ".")). For this reason, I would like to return the last item in the slice returned by the split, i.e.

for strings.Split("ex.txt", "."), I want txt

This question suggests that doing

strings.Split("ex.txt", ".")[len(strings.Split("ex.txt", ".")) - 1]

is the only way to get at it. That is, there is no -1 as in Python. This seems very wasteful to me, as I feel we are doing the same splitting operation twice.

  • Is there no better command for getting the last item of a slice in Go?
  • If no, would the best approach be to write the result of Split into a variable, or just do the above?

Thank you!

  • 写回答

3条回答 默认 最新

  • dragonpeng200811111 2018-05-12 22:48
    关注

    You should assign the results of the split to a variable, instead of calling it twice.

    ss := strings.Split(msg, ".")
    s := ss[len(ss)-1]
    

    (Notice that this allows (or maybe forces) you to deal with the case where ss is empty or something else unexpected explicitly, before indexing it.)

    If you're doing this over and over again and it offends you having to use two lines (or two lines plus error handling) instead of one you can abstract it into a function pretty easily:

    func lastString(ss []string) string {
        return ss[len(s)-1]
    }
    
    s1 := lastString(strings.Split("example.txt", "."))
    s2 := lastString(strings.Split("example.jpg", "."))
    

    After all, passing the result of a function as an argument has essentially the same effect as binding it to a variable.

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

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计