Code With Go
  • Code With Go
  • 01. What, Who, Why and Where?
  • 02. Compiled vs Interpreted languages
  • 03. Types of Type!
  • 04. Stack and Heap Memory
  • 05. Garbage Collection
  • 06. About Go
  • 07. Go Playground
  • 08. Hello, World!
  • 09. Installing Go
  • 10. Variables
  • 11. Constants
  • 12. Integers
  • 12. Floats
  • 13. Boolean
  • 14. Strings
  • 15. Complex Numbers
  • 16. If Else
  • 17. Switch
  • 18. For
  • 19. User Defined Types
  • 20. Arrays
  • 21. Slices
  • 22. Structs
  • 23. Maps
  • 24. Functions
  • 25. Defer
  • 26. Pointers
  • 27. Methods
  • Resources
    • Resources - Paid
    • Resources - Free
Powered by GitBook
On this page
  • What are Variables?
  • Declaring variables
  • Short variable declaration
  • Variable Scope
  • From the Docs

Was this helpful?

10. Variables

Naming memory locations

What are Variables?

Variables are named memory locations, that are used to refer to data in our program. General format for variable is Go is: var name type = expression

Variable names must start with letter and can contain letter and number.

Declaring variables

Variables are declared using varkeyword. Before using variables, they need to be declared. For declaring variables:

  • Use the var keyword.

  • Write a variable name.

  • Write the variable type.

  • Optionally, assign value using equals =

main.go
func main() {
	var s string
	s = "sumit"
	var i, j, k int
}

Multiple variables of same type can be declared using comma separation in name. All declared variables should be used.Variable name can not be reserved keywords.

keywords
break        default      func         
interface    select       case         
defer        go           map          
struct       chan         else         
goto         package      switch
const        fallthrough  if           
range        type         continue     
for          import       return       
var

Short variable declaration

Short variable declaration may be used to declare and initialize local variables.It takes the form name := expression.Below declarations are one and the same

main.go
func main() {
	var s string
	s = "hello, world!"
	t := "hello, world!"

	var i int
	i = 42
	j := 42
}

Variable Scope

Variables are visible only with the scope they are declared. We can access the variable so long as it’s in scope, but once a variable is no longer in scope, attempts to access it will report an error. Scope is defined by braces {}

From the Docs

Previous09. Installing GoNext11. Constants

Last updated 5 years ago

Was this helpful?

Effective Go - The Go Programming Languagegolang
Effective Go
Logo