当前位置:网站首页>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 :

We start from this .
The following example :
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
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
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

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 !
边栏推荐
猜你喜欢
Talk about MySQL indexing mechanism
Matplotlib learning notes
Multithreading starts from the lockless queue of UE4 (thread safe)
SQL server cannot find user or group when creating windows login account
Double carbon in every direction: green demand and competition focus in the calculation from the east to the West
Pagoda access changed from IP to domain name
Record several interesting XSS vulnerability discoveries
Experience of electric competition - program-controlled wind pendulum
Brief description of redo logs and undo logs in MySQL
Cynthia項目缺陷管理系統
随机推荐
Some experience in database table structure design
数据库系统概念(第十七章)
of_ find_ compatible_ Node find all nodes
Questions and answers of the labor worker general basic (labor worker) work license in 2022
数据库学习笔记(第十六章)
C# 文件打包下载
记几次略有意思的 XSS 漏洞发现
Develop a basic module with low code
Install Kubernetes 1.24
Brief introduction of class file structure and class loading process execution engine
C file package and download
数据库学习笔记(第十五章)
To vent their dissatisfaction with their superiors, Baidu post-95 programmers were sentenced to 9 months for deleting the database
中国SaaS产业全景图谱
【图像去噪】基于matlab高斯+均值+中值+双边滤波图像去噪【含Matlab源码 1872期】
Electrolytic capacitor, tantalum capacitor, ordinary capacitor
Idea remote debugging jar submitted by spark submit
Ubuntu installs MySQL compressed package for future reference
Do you agree that the salary of hardware engineers is falsely high?
Redis相关