# 10. Variables

### 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 `var`keyword. Before using variables, they need to be declared. For declaring variables:

* Use the var keyword.&#x20;
* Write a variable name.&#x20;
* Write the variable type.&#x20;
* Optionally, assign value using equals `=`

{% code title="main.go" %}

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

{% endcode %}

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.

{% code title="keywords" %}

```go
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
```

{% endcode %}

### 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

{% code title="main.go" %}

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

	var i int
	i = 42
	j := 42
}
```

{% endcode %}

### 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

{% embed url="<https://golang.org/doc/effective_go.html#variables>" %}
Effective Go
{% endembed %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.codewithgo.com/variables.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
