Welcome to the section on data types in Go! Understanding data types is fundamental to programming in any language, as they define the kind of values that can be stored and manipulated. In this tutorial, we will explore the built-in data types available in Go, their syntax, and how to use them effectively.
Go is a statically typed language, which means that every variable must have a declared type at compile time. This helps catch errors early and ensures that operations are performed on compatible types. Let's dive into the different categories of data types available in Go.
Go provides several basic types that can be categorized as follows:
The boolean type in Go is used to represent true or false values. It is denoted by the keyword bool.
var isActive bool = true
Go supports both integer and floating-point numbers:
int, int8, int16, int32, int64 for signed integers, and uint, uint8, uint16, uint32, uint64, uintptr for unsigned integers.float32 and float64.complex64 and complex128.var age int = 30
var height float64 = 5.9
Strings in Go are immutable sequences of bytes, typically representing text.
var name string = "Alice"
Let's look at some practical examples to illustrate how these data types can be used in Go.
Here is a simple example demonstrating the use of boolean values:
package main
import "fmt"
func main() {
var isLoggedIn bool = true
if isLoggedIn {
fmt.Println("User is logged in.")
} else {
fmt.Println("User is not logged in.")
}
}
<OutputBlock>
{`User is logged in.`}
### Numeric Example
This example shows how to use different numeric types:
```go
package main
import "fmt"
func main() {
var count int = 10
var price float64 = 19.99
fmt.Printf("Count: %d, Price: $%.2f\n", count, price)
}
{`Count: 10, Price: $19.99`}
</OutputBlock>
### String Example
Here is an example of using strings:
```go
package main
import "fmt"
func main() {
var greeting string = "Hello, World!"
fmt.Println(greeting)
}
<OutputBlock>
{`\`Hello, World!`}</OutputBlock>
## What's Next?
In the next section, we will explore constants in Go. Constants are values that cannot be changed after they are declared and are useful for defining fixed values within your code.
Stay tuned for more tutorials on Go!`}
</OutputBlock>