Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Go Module 2

Basics: values, types and control flow interview questions

Interview questions on “Basics: values, types and control flow”: warm-ups, then what each harder question tests and how a good answer starts.

27 questions: 7 warm-ups and 20 with model answers · Levels: Fresher to senior

Warm-up questions

Short questions with short answers, each answered in full.

  1. Fresher

    What is the zero value of a map, and what can you do with it?

    Answered in the lesson Variables, short declarations and zero values

  2. Fresher

    Is int the same type as int64 on a 64-bit machine?

    Answered in the lesson Basic types: numbers, strings, bools, conversion

  3. Fresher

    What value does iota have on each line of a const block, and when does it start again?

    Answered in the lesson Constants, untyped values and iota

  4. Fresher

    How do you write a conditional value in Go, which has no ?: operator?

    Answered in the lesson Operators, precedence and bit manipulation

  5. Fresher

    How do you write a while loop in Go, which has no while keyword?

    Answered in the lesson Control flow: if, for, range and switch

  6. Fresher

    What is the difference between %v, %+v and %#v?

    Answered in the lesson Formatted output with fmt: verbs and widths

  7. Fresher

    What is in os.Args, and what is os.Args[0]?

    Answered in the lesson Reading input: lines, arguments and fast I/O

Questions with model answers

What each question tests, the first step of a good answer and the follow-ups to expect.

  1. Fresher to mid

    A function that loads a configuration file declares var err error at the top, calls os.ReadFile inside an if block and returns err at the end. Callers get a nil error even when the file is missing. What is the likely bug, how do you confirm it, and how do you keep it out of the codebase?

    What it tests
    Knowing that := in an inner block declares new variables that shadow the outer ones, reading scopes precisely, and the tools and code shapes that prevent the bug.
    First step
    Read the call inside the if. If it says data, err := os.ReadFile(path), the := declared a second err that exists only until the block's closing brace, and the function returns its own err, which nothing assigned, so it is still nil. A test that passes a missing path and expects an error confirms it.
    Follow-ups

    From the lesson Variables, short declarations and zero values

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.

    Opening the model answers with your pass…

    Model answers open with any MySmartCoPilot pass.

    • Pro pass · 1 week₹79$2.99
    • 30 days₹179$5.99
    • 1 year₹1,699$45

    One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.

    It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  2. Fresher to mid

    You are designing a WordTally type that counts words. Callers should be able to write var t WordTally and call t.Add("go") at once, the way they use strings.Builder. How do you make its zero value useful, and what goes wrong if it holds a map?

    What it tests
    Designing a type whose zero value works, the nil-map write panic, allocating on first write with a pointer receiver, and knowing when a constructor is still the better design.
    First step
    List what the zero value of each field allows. A nil map can be read but not written, so either allocate the map on the first write, inside the method that writes, or choose fields whose zero value already works. Add must change the caller's tally, so it needs a pointer receiver.
    Follow-ups

    From the lesson Variables, short declarations and zero values

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  3. Fresher to mid

    A daily report converts each order's float64 total to cents and adds them up. After 40,000 orders it is about 2,300 cents below the bank's statement, though every order prints correctly. Why does that happen, and how would you fix the code and the stored data?

    What it tests
    Knowing why binary floating point cannot hold most decimal amounts, how small errors add up, and how to move money to integer cents with explicit rounding.
    First step
    Every order prints correctly, so look at the step that turns each float64 total into cents, before the sum. Run that exact expression on many amounts whose cents you know, such as all 10,000 from 0.00 to 99.99, count how many come out a cent short, and check whether that share of 40,000 orders explains the 2,300 cents.
    Follow-ups

    From the lesson Basic types: numbers, strings, bools, conversion

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  4. Fresher to mid

    A metric counts the bytes uploaded in an int32 field. After one large upload the dashboard shows a negative number. Explain what happened, how code could have caught it before it happened, and which type you would use instead.

    What it tests
    Knowing Go's defined wrap-around for signed integers, the range of int32, checks that run before the arithmetic, and choosing a width from the data's real range.
    First step
    Compare the total with the type's range. An int32 holds at most 2,147,483,647, about 2.1 GB of bytes, and Go's integer arithmetic wraps past the end of a range with no error, so the upload that crossed that total turned it negative. Then follow the value through every field, column and conversion on its way to the dashboard.
    Follow-ups

    From the lesson Basic types: numbers, strings, bools, conversion

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  5. Fresher to mid

    A colleague builds cache keys with key := "order:" + string(order.ID). For the IDs 65 and 9731 the keys come out as "order:A" and "order:☃". What went wrong, how does Go's tooling catch it, and how do you convert numbers to text and back safely?

    What it tests
    Knowing that string(int) converts a code point to a character, that vet's stringintconv check reports it, and the strconv functions with their errors.
    First step
    Read string(order.ID) as the specification defines it: converting an integer to a string gives the UTF-8 encoding of the character with that code, so 65 becomes "A". go vet reports the line, and go test refuses to run until it is fixed.
    Follow-ups

    From the lesson Basic types: numbers, strings, bools, conversion

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  6. Mid to senior

    Someone adds a Packed constant between Paid and Shipped in an iota block of order statuses. Orders stored in the database now show the wrong status, and no test failed. Why, and how do you make the values of an enumeration safe to store and to send?

    What it tests
    Knowing that iota numbers by position, the difference between a constant's name and its stored number, and stable encodings for stored or transmitted enumerations.
    First step
    Write out the number iota gives each constant before and after the change: iota numbers the lines of a block by position, so a line added in the middle moves every constant below it. Then find when the change was deployed, because rows written before and after it use different numbers for the same status.
    Follow-ups

    From the lesson Constants, untyped values and iota

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  7. Fresher to mid

    An API decodes a JSON body into a struct whose Status field has the type OrderStatus, an int type with constants from iota. A client sends "status": 42. What happens, and how should the type defend itself?

    What it tests
    Knowing that any int converts to a named integer type, where validation belongs, and how encoding/json uses the UnmarshalJSON and UnmarshalText methods of a type.
    First step
    encoding/json decodes 42 into the field without complaint: OrderStatus is an integer type, and a named type does not limit which numbers it holds. The struct now carries a status that no constant names, so the code that handles statuses meets a case it never planned for.
    Follow-ups

    From the lesson Constants, untyped values and iota

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  8. Fresher to mid

    Why does time.Sleep(2 * time.Second) compile while time.Sleep(n * time.Second) does not when n is an int? What is the right fix when the delay comes from a configuration file as seconds with a fraction, such as 1.5?

    What it tests
    Knowing how untyped constants take their type, why typed variables need conversions, and how to turn a fractional number of seconds into a time.Duration without losing the fraction.
    First step
    time.Second is a typed constant of type time.Duration. In 2 * time.Second the untyped 2 takes that type, but n is already an int, and an int never mixes with a time.Duration, so convert it: time.Duration(n) * time.Second.
    Follow-ups

    From the lesson Constants, untyped values and iota

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  9. Mid to senior

    You port a checksum routine from C to Go line for line, and its results change. One line is crc = crc << 4 + x & 0xF. Which operators group differently in the two languages, and how do you port bit-level code safely?

    What it tests
    Knowing Go's five precedence levels against C's longer list, spotting the expressions whose grouping changes, and porting with explicit parentheses and tests against the original.
    First step
    Group the line by each language's rules. In Go, << and & sit on level 5 with *, and + on level 4, so the line is (crc << 4) + (x & 0xF). In C, + binds more tightly than <<, and << more tightly than &, so the same text computes something else.
    Follow-ups

    From the lesson Operators, precedence and bit manipulation

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  10. Fresher to mid

    A permissions field is a uint8 of flags. Write the expressions that set, clear, toggle and test one flag, and explain why flags & ^1 does not compile while flags &^ 1 does.

    What it tests
    Using |, &^, ^ and & on flags, reading the precedence of a flag test, and knowing how unary ^ on an untyped constant meets an unsigned type.
    First step
    Write the four expressions with the flag on the right of each operator: |= to set, &^= to clear, ^= to toggle, and & with a comparison to test. Then work out the type and the value of ^1 on its own, before it meets flags, and ask whether a uint8 can hold that value.
    Follow-ups

    From the lesson Operators, precedence and bit manipulation

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  11. Fresher to mid

    A function packs colours with uint32(r<<16 | g<<8 | b), where r, g and b are uint8 values, and every packed colour comes out as just its blue part. Why, and how do you write and test the packing so the bug cannot return?

    What it tests
    Knowing the type a shift is computed in, the order of conversion and shift, masks for unpacking, and round-trip tests over many values.
    First step
    Look at the types inside the parentheses before the conversion runs: work out which type r<<16 is computed in, how many bits that type has and what is left of r after the shift. Then do the same for g<<8, and compare the result with the blue part the packed colours show.
    Follow-ups

    From the lesson Operators, precedence and bit manipulation

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  12. Fresher to mid

    A worker loop goes through a slice of jobs and switches on each job's kind. For a "stop" job the case calls break, yet the jobs after it still run. Why, and what are the ways to fix it?

    What it tests
    Knowing which statement break ends, using labelled break and continue, and choosing between a label, a return from a function and a flag.
    First step
    Find the innermost for, switch or select around the break. Here it is the switch, so break ends the switch and the loop takes the next job. Then decide what should end: the loop, which a label can name, or the whole function, which return ends.
    Follow-ups

    From the lesson Control flow: if, for, range and switch

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  13. Fresher to mid

    A crawler keeps a slice of pages to visit. It ranges over the slice and appends every new link it finds, but the pages added during the loop are never visited. Explain why, and write the loop so that they are.

    What it tests
    Knowing when a range loop reads its collection, writing a work-queue loop that sees pages added during the loop, and keeping pages from being visited twice.
    First step
    Measure it first: print the number of passes the loop makes and the length of the slice when it ends. Then read what the specification says about when a range loop evaluates its range expression, and compare that with a loop whose condition looks at len(queue) on every pass.
    Follow-ups

    From the lesson Control flow: if, for, range and switch

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  14. Fresher to mid

    A function builds a report line by ranging over a map of totals, and its test compares the line with a fixed string. The test passes on your machine and fails in CI with the same code. What is wrong, and how do you fix the function and the test?

    What it tests
    Knowing that map iteration order is not specified and changes between loops, making output deterministic by sorting keys, and writing tests that never depend on an unspecified order.
    First step
    Notice that the order of the line comes from the map loop, which the specification leaves open and the runtime varies from one loop to the next. Run the test many times with go test -count=20: it fails on some runs and passes on others with nothing changed, which shows that the order, not the arithmetic, is at fault.
    Follow-ups

    From the lesson Control flow: if, for, range and switch

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  15. Fresher to mid

    A service writes request details with log.Printf(msg), where msg is built from what the client sent. Some log lines contain %!d(MISSING) or %!s(MISSING). What causes it, how serious is it, and how do you fix it and keep it fixed?

    What it tests
    Reading a format string the way Printf reads it, recognising fmt's markers, choosing a call that cannot break, and keeping the mistake out of the code with tooling.
    First step
    Find one garbled log line and the request text behind it, and put them side by side. Look for a percent sign in the text at the place where the marker appears, then ask what log.Printf does with its first argument, the one that holds that text.
    Follow-ups

    From the lesson Formatted output with fmt: verbs and widths

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  16. Fresher to mid

    Print a table of item names, quantities and amounts kept in paise so that the columns line up, for names of any length. Which verbs and widths do you use, and what goes wrong when a name is longer than its column?

    What it tests
    Using widths, the - flag and zero padding, printing money from whole paise, sizing a column from the data with a * width, and knowing the limits of counting runes.
    First step
    Choose a verb and a width per column: %-Ns for the name, left-aligned, %4d for the quantity and %d.%02d for the amount, with a total width that matches the header. Then decide what a name longer than N should do, because a width is only a minimum and a long name pushes the rest of its line to the right.
    Follow-ups

    From the lesson Formatted output with fmt: verbs and widths

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  17. Fresher to mid

    A type Paise int64 has func (p *Paise) String() string, which writes 35550 paise as rupees and paise. fmt.Println(&p) uses it, but fmt.Println(p) and a printed []Paise show bare numbers. Explain why, fix it, and say how you keep such a method from breaking.

    What it tests
    Knowing method sets and pointer receivers, the order of fmt's checks, the recursion trap inside String, and how String applies to elements and struct fields.
    First step
    Ask which types have the String method. Compare the receiver in its declaration with the type of what each call hands to fmt: p, &p and the elements of a []Paise. Then check what fmt prints for a value that has no String method.
    Follow-ups

    From the lesson Formatted output with fmt: verbs and widths

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  18. Fresher to mid

    A log processor reads files line by line with bufio.Scanner. On some files it reports far fewer lines than the file has, and no error appears anywhere. What is the likely cause, how do you prove it, and how do you fix it for good?

    What it tests
    Knowing the Scanner's limit on the size of a token, checking Err after the loop, choosing a limit as a memory budget, and knowing when bufio.Reader fits better.
    First step
    Look at what the code does after the loop ends: does it ask the Scanner why it stopped? Print sc.Err() for one file that comes up short, and look at the line just after the last one that was counted.
    Follow-ups

    From the lesson Reading input: lines, arguments and fast I/O

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  19. Fresher to mid

    A solution to a coding test reads a million numbers with fmt.Scan and runs past its time limit, although the same code is instant on small inputs. What do you change, and how do you show that the change is what made it fast?

    What it tests
    Knowing why fmt.Scan on os.Stdin is slow, reading through a buffer with strconv, writing output through a flushed bufio.Writer, and measuring the effect instead of guessing.
    First step
    Time the input on its own: read the numbers and do nothing else. If reading alone takes seconds, the algorithm is not the problem, and the way the program reads standard input is the part to change and measure again.
    Follow-ups

    From the lesson Reading input: lines, arguments and fast I/O

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  20. Fresher to mid

    A command-line tool prints its results through a bufio.Writer. Most runs are fine, but when it exits with an error status its last lines are missing, and on short runs all of its output is. Why, and how do you change the structure of the program?

    What it tests
    Knowing when a bufio.Writer hands its output on, which ways of ending a program skip deferred calls, and structuring main so that output arrives and errors are reported before the exit.
    First step
    Find where the program ends on the error path, and what happens to the bufio.Writer before that point. Then compare a failing run that lost everything with one that lost only its last lines: how much did each write before it stopped?
    Follow-ups

    From the lesson Reading input: lines, arguments and fast I/O

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes

All Go interview questions · The Go track

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.