gpt4 book ai didi

go - golang 中的早期或晚期参数评估?

转载 作者:IT王子 更新时间:2023-10-29 01:58:06 25 4
gpt4 key购买 nike

在我的程序中,我以这种方式进行了一系列顺序检查:

var value int

if !(ParseOrFail(inputStrVal, &value) &&
Validate(value)) {
return SomeErr
}

我知道只有当 ParseOrFail 返回 true 时才会调用 Validate,但我不确定是否在所有这些情况下它都会获得更新的值。

这样做对吗?或者我必须将指针传递给 Validate 吗?

Playground 链接:https://play.golang.org/p/l6XHbgQjFs

最佳答案

The Go Programming Language Specification

Expressions

An expression specifies the computation of a value by applying operators and functions to operands.

Operands

Operands denote the elementary values in an expression. An operand may be a literal, a (possibly qualified) non-blank identifier denoting a constant, variable, or function, a method expression yielding a function, or a parenthesized expression.

Order of evaluation

At package level, initialization dependencies determine the evaluation order of individual initialization expressions in variable declarations. Otherwise, when evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, and communication operations are evaluated in lexical left-to-right order.

Calls

Given an expression f of function type F,

f(a1, a2, … an)

calls f with arguments a1, a2, … an. Except for one special case, arguments must be single-valued expressions assignable to the parameter types of F and are evaluated before the function is called. The type of the expression is the result type of F. A method invocation is similar but the method itself is specified as a selector upon a value of the receiver type for the method.

Logical operators

Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.

&&    conditional AND    p && q  is  "if p then q else false"
|| conditional OR p || q is "if p then true else q"
! NOT !p is "not p"

您的代码的行为在 The Go Programming Language Specification 中定义。

var value int

if !(ParseOrFail(inputStrVal, &value) && Validate(value)) {
return SomeErr
}

或者,在伪代码中,

ParseOrFail arguments are evaluated
ParseOrFail is called
if ParseOrFail == true
Validate arguments are evaluated
Validate is called

也就是说,在您的示例 ( https://play.golang.org/p/l6XHbgQjFs) 中,延迟评估。

关于go - golang 中的早期或晚期参数评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43412117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com