在Go中测试空字符串的最佳方法是什么? [英] What is the best way to test for an empty string in Go?

查看:93
本文介绍了在Go中测试空字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 如果len(mystring)(测试非空字符串) )> 0 {} 

或者:

  if mystring!={} 

还是别的什么? / b>

解决方案

这两种样式都用在Go的标准库中。

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

可以在 strconv 包: http://golang.org/src/pkg/strconv/atoi.go

  if s!={...} 
encoding / json
包中找到p $ p>

http://golang.org/src/pkg/encoding/json/encode.go

<两者都是惯用的,而且足够清晰。这是一个个人品味和清晰度的问题。



Russ Cox在 golang-nuts线程


使代码变得清晰的一种。
如果我要查看元素x,我通常会编写

len(s)> x,即使对于x == 0,但是如果我关心

是这个特定的字符串我倾向于写s ==。假设一个成熟的编译器会将

len(s)== 0和s ==编译成相同的,高效的代码。

现在6g等编译s ==到一个函数调用

,而len(s)== 0不是,但这是我的工作清单来解决。



清除代码。



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

if len(mystring) > 0 { }

Or:

if mystring != "" { }

Or something else?

解决方案

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 and 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.

这篇关于在Go中测试空字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆