I'm following this tutorial, specifically exercise 8:
http://tour.golang.org/#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.
The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car"
In a nutshell, the [:] operator allows you to create a slice from an array, optionally using start and end bounds.
The * character is used to define a pointer in both C and Go. Instead of a real value the variable instead has an address to the location of a value. The & operator is used to take the address of an object.
enter the walrus operator An expression evaluates to a value. A statement does something. In other words, the walrus operator allows us to both assign a value to a variable, and to return that value, all in the same expression.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With