Variables and Types
Learn how to declare variables, understand Go's type system, and master the basics of working with different data types in Go.
- •How to declare and initialize variables in Go
- •Understanding basic types in Go: integers, floats, strings, and booleans
- •Type inference and explicit type declarations
- •Constants and their usage
- •Zero values and type conversions
Variable Declaration
Go offers several ways to declare variables. The most explicit way uses the var keyword:
var name string = "John"
var age int = 30
var isStudent bool = trueGo can also infer the type from the value, making your code more concise:
var name = "John" // type inferred as string
var age = 30 // type inferred as int
var isStudent = true // type inferred as boolShort Variable Declaration
Inside functions, you can use the short declaration operator := which is the most common way to declare variables:
func main() {
name := "John"
age := 30
isStudent := true
fmt.Println(name, age, isStudent)
}Pro tip
The := operator can only be used inside functions. For package-level variables, you must use var.
Basic Types
Go has several built-in types. Here are the most common ones:
int- Platform-dependent integerint8, int16, int32, int64- Fixed-size integersfloat32, float64- Floating-point numbers
string- Text databool- true or falsebyte- Alias for uint8
var count int = 42
var price float64 = 19.99
var message string = "Hello, Go!"
var isActive bool = trueZero Values
Variables declared without an explicit initial value receive their zero value:
var i int // 0
var f float64 // 0.0
var b bool // false
var s string // "" (empty string)Practice Exercise
Create a program that declares variables for personal information and prints them:
- First name and last name (strings)
- Age (integer)
- Height in meters (floating-point number)
- Whether you are a student (boolean value)
Print all values formatted using fmt.Printf.