Variables
package main import "fmt" func main() { var x string = "Hello World" fmt.Println(x) }
OR
package main import "fmt" func main() { var x string x = "Hello World" fmt.Println(x) }
$ go run main.go Hello World
package main import "fmt" func main() { var x string x = "first" fmt.Println(x) x = "second" fmt.Println(x) }
$ go run main.go
fist second
var x string = "hello" var y string = "world" fmt.Println(x == y)
This program should print
false
because hello
is not the same as world
. On the other hand:var x string = "hello" var y string = "hello" fmt.Println(x == y)This will print
true
because the two strings are the same.Since creating a new variable with a starting value is so common Go also supports a shorter statement:
x := "Hello World"
Notice the
:
before the =
and that no type was specified. The type is not necessary because the
Go compiler is able to infer the type based on the literal value you
assign the variable. (Since you are assigning a string literal, x
is given the type string
) The compiler can also do inference with the var
statement:var x = "Hello World"
The same thing works for other types:
x := 5 fmt.Println(x)
Generally you should use this shorter form whenever possible.
Example:
dogsName := "Max" fmt.Println("My dog's name is", dogsName)
$ go run main.go
My dog's name is Max