Getting started
Zero values, declarations, printing, types, operators, and control flow.
What is the value of city after var city string?
All questions with explanations (answers shown)
1. What is the value of
cityaftervar city string?Answer:
""— the empty stringEvery type has a zero value and a string’s is
"". Only pointers, slices, maps, channels, funcs and interfaces arenil. Go has noundefined.2. Which of these does NOT compile?
Answer:
var b float64 = someIntGo never converts between typed numeric values implicitly. You must write
float64(someInt). Only untyped constants like25adapt to the type they are assigned to.3. You import
"os"but never use it. What happens?Answer: A compile error
Unused imports and unused local variables are compile errors in Go. Go does this on purpose: it stops dead code from building up.
4. Which verb prints the type of a value, such as
intorstring?Answer:
%T%Tprints the type:fmt.Printf("%T", 3.5)givesfloat64.%vprints the value,%sa string, and%qa quoted string.%Tis the quickest way to check what type Go inferred for a:=variable.5. What does
fmt.Println(7 / 2)print?Answer:
3Both operands are integers, so this is integer division and it truncates toward zero. If you want
3.5, convert first:float64(7) / 2.6. What is
string(65)?Answer:
"A"Converting a number to a string converts a code point to a character. To get the text
"65"you needstrconv.Itoa(65).go vetflags the common form of this mistake.7. Which loop keyword does Go have?
Answer: Only
forThere is one loop keyword. Drop the init and post clauses and
foris a while loop; drop everything and it is infinite.8. In a Go
switch, when do you needbreakat the end of a case?Answer: Never — cases do not fall through
Go does not fall through. If you want the C behaviour, the keyword is
fallthrough, and you will rarely need it.9. What does
var i int8 = 127; i++leave ini?Answer:
-128Integer overflow wraps around with no panic and no warning. Narrowing conversions truncate the same way (
int8(x)withx := 200gives-56), so check the range before converting to a smaller type.