# 11. Constants

### What are constants?

A `const` declaration defines named values that look syntactically like variables but whose value is constant.Instead of the `var` keyword, we use the `const` keyword.A value must be assigned while declaring constants.Constants only exists during compile time!

### Declaring constants

Constants are declared using `const` keyword.

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

```go
const pi = 3.14
```

{% endcode %}

### Constant Block

Similar to variable block, we can also have constant block.

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

```go
const (
	pi         = 3.14
	daysInWeek = 7
)
```

{% endcode %}

### IOTA

`iota` can be used to create enumerated constants. It is also called as constant generator.

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

```go
const (
	Sunday int = iota
)

func main() {
	fmt.Println(Sunday)
}
```

{% endcode %}

Benefits of using iota is that it will increment itself for next const declaration in same const block.

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

```go
const (
	Monday int = iota + 1
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	Sunday
)

func main() {
	fmt.Println(Monday, Tuesday, Wednesday, Thursday, 
	Friday, Saturday, Sunday)
}
// output : 1 2 3 4 5 6 7
```

{% endcode %}

### From the Docs

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

### Blog Posts

{% embed url="<https://blog.golang.org/constants>" %}

{% embed url="<https://github.com/golang/go/wiki/Iota>" %}

{% embed url="<https://dlintw.github.io/gobyexample/public/constants-and-iota.html>" %}

{% embed url="<https://splice.com/blog/iota-elegant-constants-golang/>" %}


---

# 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/constants.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.
