8

I am going through the Go source code of ast.go at here,and there are 3 types of interfaces that are Expression,Statement and Declaration. But only with the source code I couldn't figure out the difference between them.What I could figure out is that expression results in a object that could be assigned or compared or used as parameter,while statements are some flow control like if-else or for loop. But I found some definitions like

    // An IncDecStmt node represents an increment or decrement statement.
    IncDecStmt struct {
            X      Expr
            TokPos token.Pos   // position of Tok
            Tok    token.Token // INC or DEC
    }

shouldn't it be a expression?I feel confused how to distinguish expressions and statements,are there any rules?

ggaaooppeenngg
  • 1,323
  • 3
  • 17
  • 27

2 Answers2

7

Those are common terms in CS. An expression produces a value while a statement often doesn't (this last point depends of the language, in fact, some languages consider expressions as a subcategory of statements).

From Wikipedia :

In most languages, statements contrast with expressions in that statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.

In Go an expression may be used as statement.

Your confusion seems to come from the increment and decrement operators. In Go, contrary to most C-based languages, the increment and decrement statements don't produce a value, they're statements and not expressions. That is, you may not write

b := a++
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
7

The Golang spec uses those terms:

  • Expressions: specifies the computation of a value by applying operators and functions to operands.
  • Statements: control execution
  • Declarations (and scope): binds a non-blank identifier to a constant, type, variable, function, label, or package

The IncDecStmt is specified as

IncDecStmt = Expression ( "++" | "--" ) .

The "++" and "--" statements increment or decrement their operands by the untyped constant 1.

It uses an expression, but remains a statement (don't produce a new value).

Note: an untyped constant is when you declare a constant without explicitly mentioning its type:

i := 0 # int8? uint8? int16? ...

An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required, for instance, in a short variable declaration such as where there is no explicit type.

The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250