有没有一种特定和正确的方法来执行单参数三元运算符?

huangapple go评论62阅读模式
英文:

Is there a specific and correct way to do single argument ternary operators?

问题

我有一个布尔常量,我用它来确定是否执行某个操作。我相当喜欢三元运算符,因为它们在大多数情况下看起来很简洁。

在我的情况下,如果常量为真,则应执行该操作,如果常量为假,则不应执行任何操作。

对我来说,我会这样处理

BOOLEAN_CONSTANT ? doAction() : false;

但我不确定这是否是“正确”的方式。

是否有文档化和/或建议的方法来使用只有一个参数的三元运算符?

如果没有,我将使用if语句,但它们需要更多的行数(除非您使用单行if,这不是我遵循的编码范例的一部分)。


似乎这个问题引发了关于个人首选编码风格的意见,从而引发了不同的回答。我遵循一种适合我的特定风格,如果您遵循不同的风格,那完全没问题。

我考虑关闭这个线程,但我将其留给管理员来决定,因为我无法判断它是否符合SO指南的有用性分类。

英文:

I have a boolean constant that I use to determine whether I do an action. I'm quite fond of ternary operators because they look clean in most scenarios.

In my case, the action should be done if the constant is true and nothing should happen if the constant is false.

To me, I would handle it like this

BOOLEAN_CONSTANT ? doAction() : false;

but I'm unsure about whether this is "correct".

Is there a documented and/or recommended way to use the ternary operator with 1 argument?

If there isn't, i'll just use an if statement, but they take up more lines (unless you use a single line if which isn't part of the coding paradigm I follow).


It seems as if this question provokes opinionated responses down to the preferred coding style of a person. I follow a certain style that suits what I do, if you follow a different one that's completely okay.

I considered closing this thread, but I'll leave it to a moderator since I can't judge whether its existence would be classified as useful by SO guidelines.

答案1

得分: 1

你可以使用 && 来仅在第一个表达式为真时评估第二个表达式:

BOOLEAN_CONSTANT && doAction();

英文:

You can use && to evaluate the second expression only if the first expression is truthy:

BOOLEAN_CONSTANT && doAction();

huangapple
  • 本文由 发表于 2023年6月21日 22:56:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76524644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定