笑故挽风 2013-09-03 14:02 采纳率: 100%
浏览 201
已采纳

在 Go 中测试空字符串的最佳方法是什么?

Which method is best (more idomatic) for testing non-empty strings (in Go)?

if len(mystring) > 0 { }

Or:

if mystring != "" { }

Or something else?

转载于:https://stackoverflow.com/questions/18594330/what-is-the-best-way-to-test-for-an-empty-string-in-go

  • 写回答

6条回答 默认 最新

  • bug^君 2013-09-03 14:45
    关注

    Both styles are used within the Go's standard libraries.

    if len(s) > 0 { ... }
    

    can be found in the strconv package: http://golang.org/src/pkg/strconv/atoi.go

    if s != "" { ... }
    

    can be found in the encoding/json package: http://golang.org/src/pkg/encoding/json/encode.go

    Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.

    Russ Cox writes in a golang-nuts thread:

    The one that makes the code clear.
    If I'm about to look at element x I typically write
    len(s) > x, even for x == 0, but if I care about
    "is it this specific string" I tend to write s == "".

    It's reasonable to assume that a mature compiler will compile
    len(s) == 0 and s == "" into the same, efficient code.
    Right now 6g etc do compile s == "" into a function call
    while len(s) == 0 is not, but that's been on my to-do list to fix.

    Make the code clear.

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大