Oct 22, 2018

[Go] Go2

Reference:
https://dave.cheney.net/paste/the-past-present-and-future-of-go2.pdf
https://blog.golang.org/go2draft

Top three pain points for Go developers:

  • Dependency management – modules
  • Error handling – check, handle, and error values
  • Generics


As for Go Modules, can read the summary here:


Error Handling:
Current pain: Writing lots of similar code.
result, err := callee()
if err != nil {}
Go2 introduces key word 'check',
takes 2 arguments, i.e value to return, and error.
'check' returns the value or panic iff error is not nil.

Go2 introduces key word 'handle', if err is not nil,
'handle' jumps in takes the control of code flow.

Inspecting Errors:
I used this trick in the production code, the idea is
type embedded with error interface.

Go2 introduces 'type Wrapper interface' with member function 'Unwrap() error'
and 2 new functions:
errors.Is
errors.As

Sum up:
  • check and handle for cleaning up error handling boilerplate.
  • errors.Is and errors.As for error inspection.

Generics: (Above is kinda syntax sugars, this one is the killer feature)

func Max(a, b T) T {
 if a > b {
 return a
 }
 return b
}

Type substitution is the problem.
Well, golang folks just being so hesitated mentioning C++, lol.
C++'s template isn't object oriented like Java's bound type,
thus more close to the use case golang has here.

Go2 introduces the idea of 'contract'.
(C++'s 'concept' in C++20 or traits with SFINAE before C++20)

How to use contract in Go2?

// Isn't it familar? static function with traits testing type's operator support in C++
contract comparable(t T) {
 t > t
 t << 1
}

// template<typename T> which is way more clear, IMO.
func Max(type T comparable)(a, b T) T {
 if a > b {
 return a
 }
 return b
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.