Difference between := and = operators in Go

前端 未结 9 1410
野趣味
野趣味 2020-12-12 10:45

What is the difference between the = and := operators, and what are the use cases for them? They both seem to be for an assignment?

9条回答
  •  旧巷少年郎
    2020-12-12 11:16

    := is a short-hand for declaration.

    a := 10
    b := "gopher"
    

    a will be declared as an int and initialized with value 10 where as b will be declared as a string and initialized with value gopher.

    Their equivalents using = would be

    var a = 10
    var b = "gopher"
    

    = is assignment operator. It is used the same way you would use it in any other language.

    You can omit the type when you declare the variable and an initializer is present (http://tour.golang.org/#11).

提交回复
热议问题