次のコードは、ゴー1.6または1.7で構文エラー(ステートメントの終わりに予期せぬ++)を生成します。速記リターン
package main
import "fmt"
var x int
func increment() int {
return x++ // not allowed
}
func main() {
fmt.Println(increment())
}
が、これは許されないでしょうか?
次のコードは、ゴー1.6または1.7で構文エラー(ステートメントの終わりに予期せぬ++)を生成します。速記リターン
package main
import "fmt"
var x int
func increment() int {
return x++ // not allowed
}
func main() {
fmt.Println(increment())
}
が、これは許されないでしょうか?
Goの++
と--
が式ではなく、式ではないため、エラーです。Spec: IncDec Statements(およびステートメントには返される結果がありません)。推論のために
、囲碁のFAQを参照してください。Why are ++ and -- statements and not expressions? And why postfix, not prefix?
Without pointer arithmetic, the convenience value of pre- and postfix increment operators drops. By removing them from the expression hierarchy altogether, expression syntax is simplified and the messy issues around order of evaluation of ++ and -- (consider f(i++) and p[i] = q[++i]) are eliminated as well. The simplification is significant. As for postfix vs. prefix, either would work fine but the postfix version is more traditional; insistence on prefix arose with the STL, a library for a language whose name contains, ironically, a postfix increment.
あなたが書いたコードが唯一のように書くことができます。
func increment() int {
x++
return x
}
そして、あなたは何も渡さずにそれを呼び出す必要があります:
fmt.Println(increment())
assiを使用して1行に書き込もうとすると、 gnment、例えば:
func increment() int {
return x += 1 // Compile-time error!
}
しかしassignmentも声明であり、したがって、あなたはコンパイル時にエラーが発生しますので、これはまた、ゴーでは動作しません:
syntax error: unexpected += at end of statement