Skip to content

proposal: Go 2: improve error handling with “??” keyword for a special case #37243

Closed
@infeno

Description

@infeno

Would you consider yourself a novice, intermediate, or experienced Go programmer?
Intermediate

What other languages do you have experience with?
PHP, Swift, Javascript

Would this change make Go easier or harder to learn, and why?
Easier to read and less to type.

Has this idea, or one like it, been proposed before?
No, I like to change the meaning of ?? for a special case

Who does this proposal help, and why?
I have seen different ideas for error handling and adding more characters seem requires more time to learn and explaining how it works, why not add 2 symbols?
#21161
#32437
#37165

What is the proposed change?
Propose to add ?? as a shorthand for if err != nil

Is this change backward compatible?
This is a new keyword in additional to the existing ones.

Show example code before and after the change.

Existing approach is explicit and verbose

data, err := getJSONFile(“1.json”)
if err != nil {
	fmt.Println(err)
}

ok := getJSONFile(“1.json”); if !ok {
	fmt.Println(ok)
}

The is valid:
https://github.com/evanw/esbuild/blob/master/src/esbuild/main/main.go#L58

expr, ok := parser.ParseJson(log, source)	
done()
if !ok {
	return false
}

New approach for fast typing

This method is an additional keyword, allowing ?? to be translated into if err != nil behind the scene.

data, err := getJSONFile(“1.json”) ?? {
	fmt.Println(err)
}

err := getJSONFile(“1.json”) ?? {
	fmt.Println(err)
}
  1. Does not need to repeat if err != nil all the time when ?? keyword took <1 second to type.
  2. Less noise, more productivity, will probably have an impact on developers’ pattern.
  3. It purpose is strictly for handling error scenario since ?? is not implemented in Go.
  4. The shortest keyword, in return we get the best readability.

What is the cost of this proposal? (Every language change has a cost).
* What is the compile time cost?
Negligible, as it can be translate behind the scene.

Can you describe a possible implementation?
No

How would the language spec change?
No

Orthogonality: how does this change interact or overlap with existing features?
This change enable developers to type less and improve readability.

Is the goal of this change a performance improvement?
Compiler: no, Developer: yes

Does this affect error handling?
Yes

  • Is this about generics?
    No

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions