dongzhan5246 2013-09-03 14:02
浏览 34
已采纳

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

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

if len(mystring) > 0 { }

Or:

if mystring != "" { }

Or something else?

  • 写回答

8条回答 默认 最新

  • douzhu3367 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.
    ...

    Make the code clear.

    As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)