Table of Contents
A Go test question (single choice)
分析程序" >分析程序
具体过程" >具体过程
总结" >总结
Home Backend Development Golang Can you get this Go question right? More than 80% of people got it wrong...

Can you get this Go question right? More than 80% of people got it wrong...

Aug 08, 2023 pm 04:35 PM
golang go language


While surfing recently, I saw Bartłomiej Płotka, chief software engineer of Redhat and maintainer of Prometheus and other projects, posted on twitter A Go "exam question" is meant to test everyone.

Can you get this Go question right? More than 80% of people got it wrong...

The questions are as follows:

func aaa() (done func(), err error) {
 return func() { 
   print("aaa: done") 
 }, nil
}

func bbb() (done func(), _ error) {
 done, err := aaa()
 return func() { 
   print("bbb: surprise!"); 
   done() 
 }, err
}

func main() {
 done, _ := bbb()
 done()
}
Copy after login

The answer options are as follows:

A Go test question (single choice)



  • ##C: Keep outputting and never end

##


想想原因,思考一下输出结果是什么?是 A,还是 D?还是三短一长,选 B?

分析程序

缩小范围,核心关注到这块代码。如下:

func bbb() (done func(), _ error) {
 done, err := aaa()
 return func() { 
   print("bbb: surprise!")
   done() 
 }, err
}
Copy after login

在最后一行的这个闭包(匿名函数)中,大家可能认为程序调用了函数 aaa 所返回的 done 值来输出程序,应当是:

aaa: done
Copy after login

这个想法是错误的,程序没有这么去运作。

原因在于 return 实际上是一个赋值语句。结合程序,可以看到函数 bbb 的第一个返回值是 done 参数。

如下:

func bbb() (done func(), _ error)
Copy after login

也就是在函数 bbb 在程序最后执行 return 语句后,会对返回变量 done 进行赋值,自然该值不会是由函数 aaa 所设置的了。

这是一个关键的地方。

具体过程

这个程序输出结果是什么呢?

会不断地递归,疯狂输出 “bbb: surprise!”,直至栈溢出,导致程序运行出错,最终中止

同学就疑惑了,怎么又多出了个递归?

我们再看看程序:

func main() {
 done, _ := bbb()
 done()
}

func bbb() (done func(), _ error) {
 ...
 return func() { 
   print("bbb: surprise!"); 
   done() 
 }, err
}
Copy after login

本质上在函数 bbb 执行完毕后, 变量 done 已经变成了一个递归函数。

递归的过程是:函数 bbb 调用变量 done 后,会输出 bbb: surprise! 字符串,然后又调用变量 done。而变量 done 又是这个闭包(匿名函数),从而实现不断递归调用和输出。

最终结果如下:

b: surprise!bbb: surprise!bbb: surprise!runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc0200e0380 stack=[0xc0200e0000, 0xc0400e0000]
fatal error: stack overflow

runtime stack:
runtime.throw(0x1074b5a, 0xe)
        /usr/local/Cellar/go/1.16.6/libexec/src/runtime/panic.go:1117 +0x72
runtime.newstack()
        /usr/local/Cellar/go/1.16.6/libexec/src/runtime/stack.go:1069 +0x7ed
runtime.morestack()
        /usr/local/Cellar/go/1.16.6/libexec/src/runtime/asm_amd64.s:458 +0x8f
...
Copy after login

也就是正确答案是:D,程序最终运行出错。

一直调用一直爽,直至栈溢出程序崩溃。

总结

这位大佬出的题目,本质上是比较烦人的,其结合了函数返回参数的命名用法。

如果我们把这个函数的返回参数命名去掉,就可以避开这个问题。如下:

func bbb() (func(), error) {
 ...
 return func() { 
   print("bbb: surprise!"); 
   done() 
 }, err
}
...
Copy after login

输出结果为 "bbb: surprise!"。

很多 Go 的同学在日常代码编写的时候不会用到或注意到。但如果写的时候有类似案例代码中的模式,就会排查许久都查不到。

这是个有警惕意义的题目,你觉得呢?

The above is the detailed content of Can you get this Go question right? More than 80% of people got it wrong.... For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...

See all articles