DEV Community

Francis Sunday
Francis Sunday

Posted on • Updated on

Getting Started with Go - Variables

In the previous article - Golang - Getting Started, I wrote an intro to the Go programing language, and how to setup a development environment for your platform. In this article, we're going to talk about variables in Go.

What is a Variable?

A Variable, is the name given to a memory location to store a value of a specific type. In Go, there are various syntaxes to declare variables:

Single variable declaration

package main

import "fmt"

func main() {
  var bsLine string = "Man's not hot!"

  fmt.Println(bsLine)
}
Enter fullscreen mode Exit fullscreen mode

var bsLine string declares a variable named bsLine of type string. We have not assigned any value for the variable. We assigned that variable a value of a string Man's not hot!. If there isn't any value assigned to a variable declaration, go automatically initializes it with the zero value of the variable's type. If you run this program, you'd see the following output:

$ cd $HOME/go/getting-started

$ go run variables.go

Man's not hot!
Enter fullscreen mode Exit fullscreen mode

Variable Type Inference

If a variable has an initial value, Go will automatically be able to infer the type of that variable using that initial value. Hence if a variable has an initial value, the type in the variable declaration can be omitted.

package main 

import "fmt"

func main() {

  var tip = 300 // type inference happening here!

  fmt.Println("Let's tip him $", tip) // Let's tip him $300
}
Enter fullscreen mode Exit fullscreen mode

Multiple Variable Assignment

In Go, you can declare or assign values to multiple variables in a single statement:

package main

import "fmt"

func main() {

  var day, month, year int = 19, 11, 2017

  fmt.Printf("This article was posted on %d-%d-%d", day, month, year) // This article was posted on 19-11-2017
}
Enter fullscreen mode Exit fullscreen mode

Multiple assignments with different types, is that possible?

Yes it is. There's a different syntax for achieving this:


package main

import "fmt"

func main() {

  var (
    name string = "Francis Sunday"
    alias string = "codehakase" 
  )

  fmt.Printf("Hi I'm %s, in the tech world I'm referred to as %s", name, alias)
}
Enter fullscreen mode Exit fullscreen mode

The above code will print Hi I'm Francis, in the tech world I'm referred to as codehakase.

Any shorthands?

Yes, there's a shorter way to declare variables, by using the special assignment operator :=

package main

import "fmt"

func main() {

  publishDate := "19/11/2017"

  fmt.Println("Date: ", publishDate) // Date: 19/11/2017
}

Enter fullscreen mode Exit fullscreen mode

Gotchas

Declaring non-new variables


package main

import "fmt"

func main() {

  name, gender := "Francis", "male"

  fmt.Printf("Name: %d, Gender: %d", name, gender)

  gender := "female"

  fmt.Println("New gender: ", gender) //
}

Enter fullscreen mode Exit fullscreen mode

The above code, declares and assigns values to two variables name and gender, and prints a formatted string below it. This program would panic immediately after the first print statement. it will throw error no new variables on left side of :=, because both the variables have already been declared and there are no new variables in the left side of :=. So if we needed to change the value of gender, we'd use the equal to operator = instead of :=.

...

gender = "female"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hey! you've done a great job reaching this far, hopefully, you now understand how variables are defined in Go, and how to write simple programs that store data in variables. In the next article in the series, I'll be writing about Types in Go, so stay tuned.

If you missed the previous article, go check it out HERE.

I'm certain I may have missed something, do me a favour and report this dude in the comments section below XD.

You can checkout my Technical Blog, and follow me on Twitter @codehakase

Top comments (6)

Collapse
 
plutov profile image
Alex Pliutau

I think this post also can mention, that in Go is required that your code uses assigned variable. If not - it will panic as well. And to avoid this we can use _, like _, err := func().

Collapse
 
codehakase profile image
Francis Sunday

Yeah, I will be addressing that in a later article, thanks for checking it out though

Collapse
 
vivekshashank profile image
Shashank Vivek • Edited

Thanks for writing this. though In the multiple variable assignment code i feel %d should be there instead of %s.

Collapse
 
codehakase profile image
Francis Sunday

Thanks, will update this asap

Collapse
 
johannesvollmer profile image
Johannes Vollmer

Nice!

This program would panic immediately after the first print statement. it will throw error no new variables on left side of :=

Is that a runtime error?

Collapse
 
j3rn profile image
Jonathan Arnett

I experimented with it and it appears to be a compile-time error. I've tried a handful of different ways to make a variable's declaration non-deterministic in my code, and I haven't found a way yet (though that's no proof that it isn't possible). For instance, it appears that if you declare a variable in a if block, that variable goes out-of-scope at the end of the block.