Ad space (banner)
๐ŸนGo Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

In this lesson you will learn the basics of type conversion in Go so you can move between strings and numbers. This is for anyone searching for "Go strconv how to use".

Type conversion (casting) - string to number, number to string - is a fundamental programming operation. You use functions such as strconv.Atoi() and strconv.Itoa().

The sample code turns the string "123" into an integer with strconv.Atoi("123") and uses it in arithmetic, then turns the number 45 into a string with strconv.Itoa(45) and joins it to the word "dollars". Because a conversion can fail, most of these functions return an error alongside the value.

A common stumbling block for beginners is ignoring the error that strconv.Atoi() returns. A string that cannot be converted produces an error, and real code needs to check it.

In real-world development the standard library provides a conversion function for each target type, such as strconv.ParseFloat, and you pick to suit the job.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)