Course outline
Course / The terminal and the language

Convert in every direction

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/08-08-convert-between-types
cd 08-08-convert-between-types
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Finish three small functions that each convert a value to a different type: Dollars turns a float64 into an int, Label turns an int into text, and Narrow squeezes an int64 into an int8.

Example

If you had a distance in kilometres and a count of steps, you would write:

var Km = 4.8
var Steps = 12

func Whole() int {
	return int(Km)
}

func Text() string {
	return strconv.Itoa(Steps)
}

int(Km) cuts off the decimals and gives 4. strconv.Itoa(Steps) gives the text "12". For this to compile, the file also needs import "strconv".

Rules

  • Edit convert.go. Each function has a // TODO comment and a return line you will change.
  • Dollars returns Price converted to an int. The decimals are cut off, not rounded, so 3.99 becomes 3.
  • Label returns Number as text, using strconv.Itoa. Add import "strconv" at the top of the file.
  • Narrow returns Big converted to an int8. A value too big for an int8 wraps around, so 300 becomes 44.
  • The tests change Price, Number and Big, so use the variables. Do not type numbers into the functions.
  • Do not change the three var lines or the first line of each function.
  • Do not use string(Number): it gives a character, not the digits.

What you'll practice

Converting with int(...) and int8(...), turning a number into text with strconv.Itoa, and seeing what a conversion loses.

Run it

gonomicon fetch week-1/08-08-convert-between-types
cd 08-08-convert-between-types
gonomicon test
gonomicon submit

Hints

  1. Each function needs one conversion: a float64 to an int, an int to text, and an int64 to an int8. The conversion goes around the variable name.
  2. Dollars uses int( ... ) around Price. Narrow uses int8( ... ) around Big. Label cannot use a plain conversion, because turning a number into text needs strconv.Itoa.
  3. return int(Price), then return strconv.Itoa(Number), then return int8(Big). Label needs import "strconv" at the top of the file.

Something wrong with this lesson? Report a problem