A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
سؤال
I'm following this tutorial, specifically exercise 8:
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Specifically what does the :=
mean? Searching for Go documentation is very hard, ironically.
المحلول
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
نصائح أخرى
Keep on going to page 12 of the tour!
A Tour of Go
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
(Outside a function, every construct begins with a keyword and the := construct is not available.)
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only.
For example, var abc int = 20 is the same as abc := 20.
It's useful when you don't want to fill up your code with type or struct declarations.
:= is not an operator. It is a part of the syntax of the Short variable declarations clause.
more on this: https://golang.org/ref/spec#Short_variable_declarations
The :=
syntax is shorthand for declaring and initializing a variable, example f := "car"
is the short form of var f string = "car"
The short variable declaration operator(:=
) can only be used for declaring local variables. If you try to declare a global variable using the short declaration operator, you will get an error.
Refer official documentation for more details
According to my book on Go, it is just a short variable declaration statement exactly the same as
var s = ""
But it is more easy to declare, and the scope of it is less expansive. A := var decleration also can't have a type of interface{}. This is something that you will probably run into years later though
:= means that Golang guess which type of variable
example var number uint16 = 260 this is explicit variable declaration
var number = 260 what this means is telling to GOLANG to implicitly define what type this variable should be
number := 260 expression assignment operator same thing like before but without var and tell to GOLANG guess what type this is
:= represents a variable, we can assign a value to a variable using :=.