Course / The terminal and the language
Convert in every direction
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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// TODOcomment and areturnline you will change. DollarsreturnsPriceconverted to anint. The decimals are cut off, not rounded, so3.99becomes3.LabelreturnsNumberas text, usingstrconv.Itoa. Addimport "strconv"at the top of the file.NarrowreturnsBigconverted to anint8. A value too big for anint8wraps around, so300becomes44.- The tests change
Price,NumberandBig, so use the variables. Do not type numbers into the functions. - Do not change the three
varlines 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
- 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.
- 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.
- return int(Price), then return strconv.Itoa(Number), then return int8(Big). Label needs import "strconv" at the top of the file.