Go var Keyword

beginner
24 min

Go var Keyword

Welcome to our comprehensive guide on the Go var keyword! In this lesson, we'll explore the var keyword, its uses, and why it's essential for every Go programmer.

Let's dive right in! šŸŽÆ

What is the var Keyword in Go?

The var keyword in Go is used to declare variables. It allows you to specify a variable's name, type, and initial value.

go
var name string = "John Doe" var age int = 30

šŸ“ Note: In Go, you don't need to declare the type every time you use var. The compiler can infer the type based on the initial value.

Declaring Multiple Variables

You can declare multiple variables at once using the var keyword.

go
var ( name1 string = "Jane Smith" age1 int = 28 isMarried bool = true )

Initializing Variables

Initializing a variable means assigning it a value. You can initialize variables when you declare them, or you can leave the initial value blank and assign a value later.

go
var name string name = "John Doe"

Implicitly Typed Variables

If you don't specify a type when declaring a variable, Go will infer the type based on the initial value.

go
var x = 42 // x is an int var y = 3.14 // y is a float64

Scope of Variables

In Go, variables have function scope. This means that a variable declared inside a function is only accessible within that function.

go
func exampleFunction() { var localVar string = "Local Variable" // localVar can only be accessed within this function }

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `var` keyword in Go?

Summary

In this lesson, we've learned about the var keyword in Go, which is used to declare and initialize variables. We've also discussed implicit typing, multiple variable declarations, and the scope of variables.

Now that you understand the basics, it's time to put your newfound knowledge into practice! šŸš€

Stay tuned for our next lesson, where we'll dive deeper into Go variables and explore more advanced concepts! šŸ’”