go 笔试题精选练习题|——迹忆客-ag捕鱼王app官网

题库 > go > 练习:45

go 笔试题精选

下面代码运行时输出的结果是什么? ```go package main import ( "fmt" "time" ) func main() { ch1 := make(chan int) go fmt.println(<-ch1) ch1 <- 5 time.sleep(1 * time.second) } ```
  • 5
  • 编译不通过
  • 运行时死锁
正确答案是:c
正确率:73%

解析:

在 go 语言规范中,关于 go 语句有这么一句描述:

gostmt = "go" expression .

the expression must be a function or method call; it cannot be parenthesized. calls of built-in functions are restricted as for expression statements[2].

the function value and parameters are evaluated as usual[3] in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete.

这里说明,go 语句后面的函数调用,其参数会先求值,这和普通的函数调用求值一样。在规范中调用部分是这样描述的:

given an expression f of function type f,

f(a1, a2, … an)

calls f with arguments a1, a2, … an. except for one special case, arguments must be single-valued expressions assignable[5] to the parameter types of f and are evaluated before the function is called.

大意思是说,函数调用之前,实参就被求值好了。

因此这道题目 go fmt.println(<-ch1) 语句中的 <-ch1 是在 main goroutine 中求值的。这相当于一个无缓冲的 chan,发送和接收操作都在一个 goroutine 中(main goroutine)进行,因此造成死锁。

关于通道可以参考 go channel 缓冲详细介绍

查看笔记

扫码一下
查看教程更方便
网站地图