当前位置:网站首页>Go needs to add an arrow syntax, which is more like PHP!

Go needs to add an arrow syntax, which is more like PHP!

2022-06-13 10:49:00 Fried fish in my head

Hello everyone , I'm fried fish .

Touching fried fish on the eve of International Children's Day , See a very magical Go2 Technical proposal for , Want to add a simpler 、 Lighter anonymous function syntax .

Today, let's have a look at the fried fish .

New proposal

new Go The goal of the proposal is to add lightweight anonymous function syntax , The alias in the industry is also called “ Arrow Syntax ”, By @Damien Neil The proposed , The source of the proposal is 《proposal: Go 2: Lightweight anonymous function syntax[1]》, There are both praise and criticism :

Image

We start from this .

The following example :

import (
 "fmt"
 "math"
)

func compute(fn func(float64float64) float64float64 {
 return fn(34)
}

func main() {
 hypot := func(x, y float64) float64 {
  return math.Sqrt(x*x + y*y)
 }
 fmt.Println(hypot(512))

 fmt.Println(compute(hypot))
 fmt.Println(compute(math.Pow))
}

The above code mainly implements multiple anonymous closure functions , In fact, there is nothing in business logic . Because of the complexity of closure signature , Resulting in low code readability .

To avoid that , Many languages allow you to omit parameters and return types of anonymous functions , Because they may be derived from the context , Can be reused directly .

as follows Scala Example :

compute((x: Double, y: Double) => x + y)
compute((x, y) => x + y) // Parameter types elided.
compute(_ + _) // Or even shorter.

Rust Example :

compute(|x: f64, y: f64| -> f64 { x + y })
compute(|x, y| { x + y }) // Parameter and return types elided.

So the Go The proposal is to add this lightweight syntax to anonymous closures , Make the code look simpler , Make code more readable .

PHP Example :

$x = 1;
$fn = fn() => $x++; //  Does not affect the  x  Value
$fn();
var_export($x);  //  Output  1

Even more so .

Real case

Cap'n Proto

Go Open source library Cap'n Proto(capnproto/go-capnproto2[2]) Is an extremely fast data exchange format , Be similar to Protocol Buffers, But much faster .

The following is a snippet of its code :

s.Write(ctx, func(p hashes.Hash_write_Params) error {
  err := p.SetData([]byte("Hello, "))
  return err
})

Suppose we are Rust, The effect is as follows ::

s.Write(ctx, |p| {
  err := p.SetData([]byte("Hello, "))
  return err
})

errgroup

This errgroup Ku believes that we will not be strangers , Often used in multiple goroutine In the asynchronous scenario err Processing and synchronization .

The following is a fragment of its use :

g.Go(func() error {
  // perform work
  return nil
})

Suppose we are Scala, The effect is as follows :

g.Go(() => {
  // perform work
  return nil
})

Just look at the comparison from the number of codes , It's really simple .

Discuss

This proposal caused quite a stir and discussion in the community , There are many different views .

Grammar format

First from Go From a grammatical point of view . The grammar format is :

[ Identifier ] | "(" IdentifierList ")" "=>" ExpressionList

The example will become :

s.Write(ctx, p => p.SetData([]byte("Hello, "))

g.Go(=> nil)

It's shorter .

Reduced readability

Many small partners believe that this reduces the readability of the code , It's more difficult to understand , I have to change a few lines in my mind , To know what it means ...

Do you think , Grab a fried fish in the company . Suppose he didn't know the grammar in advance , Can he read what this code means ?

as follows :

g.Go(=> nil)

obviously , He can't 100% determine . But without this grammar , Just normal anonymous closures , It can be read . Because grammar is basically general , The arrow grammar is not .

Early design rejected

stay Go Early design , In fact the “ Arrow Syntax ”, That is, this proposal has been studied .

The grammar at that time was :

func f (x int) -> float32

Because it can't handle multiple ( Non tuple ) Return value ; Once it appears func And parameters , The arrow is superfluous , It's going to get complicated .

Although it will look more “ beautiful ”, but “ beautiful ”( Just like it looks in math ) May still be superfluous . It also looks like it belongs to a kind of “ Different ” Grammar of language .

Officials also believe that great care must be taken , Do not create special syntax for closures . Because now Go What we have is Simple and regular Grammar and logic .

Finally, I gave up the idea of adding arrow Syntax .

Replace with ellipsis

From the code example , The main causes of complexity are type declarations and structures . Therefore, it has also been proposed to use ellipsis to achieve a similar effect .

The following code :

s.Write(ctx, func(p _) _ { return p.SetData([]byte("Hello, ")) })

The advantage is that no grammar changes are required .

summary

The original intention of the author of the original proposal , Maybe we need to make anonymous closures more concise , Reduce code complexity . But in essence , What is saved is the apparent complexity .

Once this kind of “ arrow ” grammar , It may increase the cost of brain switching . When looking at the code , You have to think about it , It will increase the mental cost at the bottom .

Of course , Maybe I was wrong too . Do you think? ? Do you support Go New lightweight anonymous closure Syntax , That is commonly known in the industry “ arrow ” grammar .

Welcome to leave a message and exchange in the comment area .

Reference material

[1]

proposal: Go 2: Lightweight anonymous function syntax: https://github.com/golang/go/issues/21498

[2]

capnproto/go-capnproto2: https://github.com/capnproto/go-capnproto2


Follow and add fried fish on wechat ,

Get industry news and knowledge , Pull you into the communication group Image

Image


Hello , I'm fried fish , Published Go Bestsellers 《Go Language programming journey 》, And then to get GOP(Go The most insightful expert in the field ) Honor , Click on the blue word to see my way out of the book .

Daily sharing of high quality articles , Output Go interview 、 Work experience 、 Architecture design , Add wechat to attract readers , Communicate with you !

原网站

版权声明
本文为[Fried fish in my head]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206131041206772.html