What type conversion is
Every variable in Go has one type, fixed when the program compiles. An int stays an int, a float64 stays a float64 and a string stays a string. Type conversion creates a new value of a different type from an existing one.
Go never converts types for you behind the scenes. If you multiply a float64 by an int, the program does not compile:
count := 4
price := 2.5
// total := price * count // error: mismatched types float64 and int
total := price * float64(count)
fmt.Println(total) // 10
That strictness is deliberate: every conversion is visible in the code, so you always know where a value changes type and where it might lose information. You need conversions whenever data arrives in one form and you use it in another: a number read as text that you want to add to, an integer you want to put into a message, or a decimal you need as a whole number.
Syntax and examples
Between number types: T(x)
To convert between numeric types, write the target type as if it were a function: float64(x), int(x), int64(x). Going from int to float64 is straightforward. Going from float64 to int drops everything after the decimal point. It does not round; it truncates toward zero:
price := 9.99
fmt.Println(int(price)) // 9
loss := -9.99
fmt.Println(int(loss)) // -9, not -10
// Round first if that is what you want (import "math"):
fmt.Println(int(math.Round(price))) // 10
Between numbers and text: the strconv package
A string like "2024" is a sequence of characters, not a number, so int(...) can't turn it into one. Conversions between text and numbers live in the standard strconv package, which you import with import "strconv":
strconv.Itoa(x)turns anintinto its decimal text, sostrconv.Itoa(25)is"25". The name is short for "integer to ASCII".strconv.Atoi(s)goes the other way and returns two values: the number and anerror. The error isnilwhen the text is a valid integer.
age := 25
ageStr := strconv.Itoa(age)
fmt.Println(ageStr + " years") // 25 years
n, err := strconv.Atoi("12a")
if err != nil {
fmt.Println(err) // strconv.Atoi: parsing "12a": invalid syntax
}
fmt.Println(n) // 0
Checking err is the normal Go pattern. When parsing fails, Atoi returns 0, and without the check you couldn't tell a failed parse from the text "0".
A quick reference
| From | To | How | Example result |
|---|---|---|---|
int | string | strconv.Itoa(x) | "25" |
string | int | strconv.Atoi(s) | 2024 and an error |
float64 | int | int(x) | 9 from 9.99 |
int | float64 | float64(x) | 25 as a float |
string | float64 | strconv.ParseFloat(s, 64) | 9.99 and an error |
Common mistakes and gotchas
string(n)is notstrconv.Itoa(n). Converting an integer withstring(...)treats it as a Unicode code point, so 65 becomes"A", not"65".go vetwarns about this conversion; usestrconv.Itoafor digits.- Expecting rounding. A variable holding 2.99 converts to 2 with
int(...). Truncation toward zero also means negative values move up: -2.99 becomes -2. - Converting a constant that doesn't fit.
int(price)works on a variable, butint(9.99)written with a literal does not compile: a constant converted to an integer type must be a whole number that fits in it. - Using
int(...)on text.int("5")is a compile error; strings needstrconv. - Ignoring the error.
Atoirejects anything that isn't a plain integer, including surrounding spaces:" 42"fails. Discarding the error with_is only safe when you know the text is valid. - Narrowing integers. Converting a variable to a smaller integer type keeps only the low bits, silently: an
intholding 300 converted withint8(...)becomes 44. - Unused names. Go refuses to compile a program with a local variable or an import that is never used. That's one reason the blank identifier
_exists: it accepts a value you don't need, like the error fromAtoi.
The exercise, step by step
The lesson starts with three variables of three different types: age is an int, price is a float64 and year is a string. Your job is to create a converted copy of each.
- Integer to text. Declare
ageStrwith:=and give itstrconv.Itoa(age). It holds the string"25". - Decimal to integer. Declare
priceIntasint(price). The decimals are dropped, so it holds 9. - Text to integer.
strconv.Atoi(year)returns two values, so the declaration needs two names on the left. Keep the number inyearIntand discard the error with_, which is safe because"2024"is a valid integer.yearIntholds 2024.
age := 25
price := 9.99
year := "2024"
ageStr := strconv.Itoa(age)
priceInt := int(price)
yearInt, _ := strconv.Atoi(year)
After these lines, ageStr + "!" is valid string concatenation and yearInt + 1 is ordinary arithmetic giving 2025. Neither would compile with the original variables.
Key takeaways
- Go never converts types implicitly; you write every conversion yourself.
- Numeric conversions use the type name:
int(x),float64(x). int(...)on afloat64truncates toward zero; usemath.Roundfirst to round.- Text and numbers convert through
strconv:Itoafor int to string,Atoifor string to int. Atoireturns a value and an error; check the error unless you are sure the text is valid.string(65)is"A", not"65".