dousou2897 2016-04-09 04:58
浏览 25
已采纳

Go中的:=和=有什么区别?

I am new to Go programming language.

I noticed something strange in Go: I thought that it used := and substitutes = in Python, but when I use = in Go it is also works.

What is the difference between := and =?

  • 写回答

5条回答 默认 最新

  • douchangmian0305 2016-04-09 05:47
    关注

    = is assignment. more about assignment in Go: Assignments

    the subtly difference between = and := is when = used in variable declarations.

    General form of variable declaration in Go is:

    var name type = expression
    

    the above declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Either the type or the = expression can be omitted, but not both.

    For example:

    var x int = 1
    var a int
    var b, c, d = 3.14, "stackoverflow", true
    

    := is called short variable declaration which takes form

    name := expression
    

    and the type of name is determined by the type of expression

    Note that: := is a declaration, whereas = is an assignment

    So, a short variable declaration must declare at least one new variable. which means a short variable declaration doesn't necessarily declare all the variables on its left-hand side, when some of them were already declared in the same lexical block, then := acts like an assignment to those variables

    For example:

     r := foo()   // ok, declare a new variable r
     r, m := bar()   // ok, declare a new variable m and assign r a new value
     r, m := bar2()  //compile error: no new variables
    

    Besides, := may appear only inside functions. In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables.

    More info:

    variable declarations

    short variable declarations

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题