Skip to content

proposal: Go 2: add a "scope lifting" operator ^ for short variable declarations in if and for statements #40349

Closed
@markusheukelom

Description

@markusheukelom

Operator ^ lifts the declaration of a variable to the enclosing scope when used in if and for statements:

if ^f, err := os.Open("foo.bar"); err != nil {
	return fmt.Errorf("error opening file: %w", err)
}
f.Read() 	// ok: f is in scope now

Using ^f, the declaration of f escapes the if statement while keeping err local to the if statement.

The expression ^f, err := works just like f, err := except that if f is declared, it is declared in the enclosing block.

Other notes:

  1. ^ can only be used with if and for; anywhere else it is illegal

    To be more exact:
    - in the ShortVarDecl of the SimpleStatement of the IfStmt
    - in the InitStmt of the ForClause of the ForStmt
    - in the RangeClause of the ForStmt

  2. Single lifts are allowed only; ^^f is illegal, etc.

  3. I know that ^ is used as bitwise XOR operator; this should be no problem as for example * is also used for both derefencing and multiplication operator

  4. I chose ^ because it is a visual cue for the effect of the operation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions