Assignment operator in Go language
Assignment operator in Go language
Lately I was playing with google's new programming language Go
and was wondering why the assignment operator :=
has a colon in front of the equal sign =
Is there a particular reason why the authors of the language wanted to use name := "John"
instead of name = "John"
Answer by peterSO for Assignment operator in Go language
:=
is not the assignment operator. It's a short variable declaration. =
is the assignment operator.
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:
"var" IdentifierList = ExpressionList .
Assignment = ExpressionList assign_op ExpressionList .
assign_op = [ add_op | mul_op ] "=" .
In Go, name := "John"
is shorthand for var name = "John"
.
Answer by Fabien for Assignment operator in Go language
The :=
notation serves both as a declaration and as initialization.
foo := "bar"
is equivalent to
var foo = "bar"
Why not using only foo = "bar"
like in any scripting language, you may ask ? Well, that's to avoid typos.
foo = "bar" fooo = "baz" + foo + "baz" // Oops, is fooo a new variable or did I mean 'foo' ?
Answer by Joonazan for Assignment operator in Go language
name := "John"
is just syntactic sugar for
var name string name = "John"
Go is statically typed, so you have to declare variables.
Answer by Pravin Mishra for Assignment operator in Go language
Both are the different technique of variable declaration in Go language.
var name = "John" // is a variable declaration
AND
name := "John" // is a short variable declaration.
A short variable declaration is a shorthand for a regular variable declaration with initializer expressions but no types.
Read below for detail:
Answer by user2418306 for Assignment operator in Go language
Rob Pike explains why Go has :=
during his talk "Origins of Go" (2010).
:=
was a pseudo operator in another language codesigned by Pike called Newsquek (1989). Which had Pascal-ish notation and ability to infer type for declare and initialize idiom (page 15)
// variable: [type] = value x: int = 1 x := 1
Marginal note: Robert Griesemer brings up :=
operator answering the question "What would be one thing you take out from Go?" during QA session at Google I/O 2013. Referring to it as convenient but problematic, which renders into Douglas Crockford's "term" bad part.
In summary reasons for :=
existence in Go are purely sentimental.
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment