Monday 23 December 2013

Variables in golang

Declaring a variable in Go is a matter of using the var keyword. Let's follow on from our last piece of code and create a string, assign a value to it and then print it out.
package main

import "fmt"

func helloWorld() {
    var x string
    x = "Hello world"
    fmt.Println(x)
}
 
func main() {
    helloWorld()
}
Again, nothing spectacular here - we are simply printing out "Hello world", however, it illustrates simple variable declaration and assignment.
var x string
declares a variable for us and lets the compiler know we want it to be of type string. Next, we assign the string "Hello world" to variable x
x = "Hello world"
and finally, we print it out - just as we did before. Go is statically typed and compiled, however Go does borrow a little from dynamically typed languages by exposing a syntax that removes the need to name the variable's type. The Go compiler's ability to infer types allows us to short-cut our variable declarations. To wit, we can re-write our helloWorld function as follows:
func helloWorld() {
    x := "Hello world
    fmt.Println(x)
}
When we compile our code, Go will use type inference to assign a type to our variable for us. We are left with the security of a strongly typed language while still having the convenience of a more dynamically typed syntax. One more for the road; if you prefer to explicitly type your variable, but still enjoy assigning them immediately, the following variant of our helloWorld function will see you right:
func helloWorld() {
    var x string = "Hello world"
    fmt.Println(x)
}

No comments:

Post a Comment