duanhaodi4809 2015-07-10 00:35
浏览 51
已采纳

为什么在Go中为变量赋等号

I would like to say upfront that I'm only starting to learn about and use the Go language and also that this isn't a syntax question but more of a language design question.

In Go, assuming that you have a channel c of int, you can send on the channel using:

c <- 1

And receive from the channel into a variable v with:

v = <- c

I've read that a simple way to remember the syntax is that the "arrow" points in the direction in which information is flowing, which I think is poetic, especially being quite the Python fan. My question is why is this not taken all the way so you have the symmetric syntax:

v <- c

in order to receive from a channel? Why have the equals sign there?

I suppose the interpreter would end up with adjacent syntax tokens like:

[variable][value]

which could conceivably come from a statement like:

v 1 

So that the equals sign there allows you to reuse the usual variable assignment machinery by making that channel receipt evaluate to a value. Would it be that difficult to make the interpreter accept the version without the equals sign though? It would basically just have to treat it as a binary operator for that case.

It also seems to lead to other cases where if there are two channels c1 and c2 you have the syntax:

c2 <- <- c1

In order to read from one and transmit it into the other.


I'd like to also say that I'm not trying to elicit opinions on style but rather trying to understand the decisions drove Go to be the way it is.

  • 写回答

1条回答 默认 最新

  • duanbei3704 2015-07-10 02:14
    关注

    Combining two orthogonal operators each doing one thing is much more expressive.

    In addition to the examples provided by @sedat-kapanoglu, think how would you express the following:

    x := <-ch
    x += <-ch
    x, y = <-ch1, <-ch2
    

    Also with your proposal the following expression:

    y <- x
    

    could be a read from a channel x or a write to a channel y depending on the types x and y. Compare it to the code that uses the existing syntax:

    y = <-x
    y <- x
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧