【问题标题】:Running functions after && || operators&& || 之后运行函数运营商
【发布时间】:2023-01-24 02:27:32
【问题描述】:

&& || 运算符后如何调用函数。例如:

true && fmt.Println("will run")

false || fmt.Println("will run")

但它会抛出异常,因为它不会返回布尔值,那么该怎么做呢?

【问题讨论】:

  • 只需使用if。 Go 不像 Bash 那样提供这些语法糖。
  • 它只是无效的围棋。即使 fmt.Println 返回了一个布尔值,你也会得到 (value of type bool) is not used,因为你不能有这样一个未使用的表达式。使用 if 声明。
  • 如果您有另一个“有意义的”示例:解决方案是手动明确地评估每个操作数,因此短路评估不会影响执行哪个操作数。

标签: go


【解决方案1】:

您应该使用 if 声明,但这是实现您的目标的方法:

声明一个返回 bool 的函数:

func println(args ...any) bool {
    _, err := fmt.Println(args...)
    return err == nil
}

在表达式中使用该函数:

true && println("will run")

false || println("will run")

Expressions 在 Go 中不是 statements。您必须在某种 statement 中使用表达式。

condition := true
if condition && println("Hello World!") {
    fmt.Println("condition is true and println suceeded")
}

Run an example on the Playground

【讨论】:

  • 这是行不通的(请参阅问题的评论),如果行得通,println 已经是 builtin 的名称,应该避免使用。
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多