» Quick Introduction to Go » 1. Basics » 1.3 Variables

Variables

Go is statically typed, meaning that once a variable's type is declared, it cannot be changed.

// Declare variables
var a int
var b float64
var str string

// Assign values to variables
a = 10
b = 3.14
str = "Hello, Golang!"

Variables declared without a corresponding initialization are zero-valued. For example, the zero value for an int is 0.

You can also declare and assign values in a single line.

var x int = 5
y := 2.71 // type inference, y is inferred as float64
z := "Hi there!"

fmt.Println("x:", x)
fmt.Println("y:", y)
fmt.Println("z:", z)

You can use the shorthand := syntax to declare and initialize variables in a single line, and Go will automatically infer the data type.

Constants

You can declare constants using the const keyword. Constants are variables whose values cannot be changed once they are assigned.

// Declare constants
const pi = 3.14159
const gravity = 9.8
const greeting = "Hello, Golang!"

// Print the values of constants
fmt.Println("Pi:", pi)
fmt.Println("Gravity:", gravity)
fmt.Println("Greeting:", greeting)

You can also declare multiple constants in a single const.

const (
    monday    = "Monday"
    daysInWeek = 7
)

Constants are useful for defining values that should not be modified during the execution of the program.

Code Challenge

Calculate the area and the circumference of the circle.

Loading...
> code result goes here
Prev
Next