Lesson 10. Converting between types

 

After reading lesson 10, you’ll be able to

  • Convert between numeric, string, and Boolean types

Previous lessons covered Booleans, strings, and a dozen different numeric types. If you have variables of different types, you must convert the values to the same type before they can be used together.

Consider this

Say you’re at the grocery store with a shopping list from your spouse. The first item is milk, but should you get cow’s milk, almond, or soy? Should it be organic, skim, 1%, 2%, whole, evaporated, or condensed? How many gallons? Do you call your spouse to ask or just pick something?

Your spouse may get annoyed if you keep calling to ask for each detail. Iceberg or romaine lettuce? Russet or red potatoes? Oh, and was that 5 lbs. or 10? On the other hand, if you “think for yourself” and return with chocolate milk and french fries, that may not go over so well.

If your spouse is a programmer and you’re a compiler in this scenario, what do you think Go’s approach would be?

10.1. Types don’t mix

A variable’s type establishes the behavior that’s appropriate for it. Numbers can be added, strings can be joined. To join two strings together, use the plus operator:

countdown := "Launch in T minus " + "10 seconds."

If you try to join a number to a string, the Go compiler will report an error:

countdown := "Launch in T minus " + 10 + " seconds."        #1

10.2. Numeric type conversions

10.3. Convert types with caution

10.4. String conversions

10.5. Converting Boolean values

Summary