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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据