Start learning free

LESSON 14 OF 671 · VARIABLES

Type Conversion in Go

Lesson

Every value in Go has a type. Sometimes we need to convert a value from one type to another.

Common conversions in this lesson:

strconv.Itoa(x)      // converts an int to a string
int(x)               // converts a float64 to an int, dropping decimals
strconv.Atoi(s)      // converts a string to an int

Examples:

age := 25
ageStr := strconv.Itoa(age)  // "25"

price := 9.99
priceInt := int(price)       // 9

year := "2024"
yearInt, _ := strconv.Atoi(year) // 2024

Note that converting a float to an int drops the decimal part. It does not round.

Assignment
Follow the Coding Tutorial and convert each variable to a different type.


Hint
Use strconv.Itoa, int(...), and strconv.Atoi.

STEP 1 OF 3
    Ctrl + Enter to check