Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 77 ยท C, C++ and Systems Interview Questions

Go and Rust: Concurrency, Ownership and Error Handling

Prepare Go and Rust interviews: goroutines, channels, mutexes, nil interfaces, ownership, borrowing, lifetimes, Option and Result, with runnable programs.

Go and Rust are the two languages most often chosen for new backend infrastructure, so they appear in more interviews each year. The questions follow each language's reason for existing. Go is about simple concurrency: goroutines, channels, and the traps in slices and interfaces. Rust is about memory safety without a garbage collector: ownership, borrowing and lifetimes, and an error model built on types instead of exceptions.

All examples run on the site's Go 1.27 and Rust 1.99 runners (single file, standard library only). The deeper lessons are in the Go tutorial and Rust tutorial; the systems background (stack, heap, threads) is in C Pointers and Memory Questions and Operating Systems and Concurrency Questions.

Two answers to concurrency

Go Cheap goroutines talking over channels.
Rust The compiler rejects data races.

Both try to make shared state hard to get wrong.

1 / 2

Go: what is a goroutine, and how is it different from a thread?

Short answer: A goroutine is a function running concurrently, managed by the Go runtime rather than the operating system. It starts with a tiny stack (a few kilobytes that grows as needed), so a program can run hundreds of thousands of them. The runtime multiplexes goroutines onto a small number of OS threads (the GMP scheduler: goroutines, machine threads, processors) and moves a blocked goroutine off its thread so the thread can run another one.

The Go proverb is "Do not communicate by sharing memory; share memory by communicating." Use channels to pass ownership of data between goroutines. A channel can be unbuffered (sender and receiver meet) or buffered (the sender blocks only when the buffer is full). Closing a channel signals "no more values", and for range ch stops when it is closed and drained. Only the sender should close.

Go A worker pool and a mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Say aloud what each piece does: the WaitGroup waits for the three workers, and a helper goroutine closes results only after they are all done, so the range loop can finish. The mutex protects the shared counter; without it, the 1,000 increments would be a data race and the answer would vary. The -race detector finds such races, but the site runner does not offer it.

A classic follow-up is select, which waits on several channel operations at once and takes whichever is ready first. Combine it with time.After or a context.Context to implement timeouts and cancellation.

Go select with a timeout, and recovering from a panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go gotchas that interviewers love

Short answer: Three traps come up again and again: the typed-nil interface, slice aliasing, and defer ordering.

  • A nil pointer inside an interface is not a nil interface. An interface value holds a (type, value) pair; it equals nil only if both are empty. A function returning error that returns a typed nil pointer yields a non-nil error. Return a literal nil instead.
  • Slices share a backing array until append exceeds the capacity, when Go allocates a new one. Two slices appended from the same base can overwrite each other.
  • defer runs last-in-first-out when the function returns, and the arguments are evaluated when the defer statement executes.
  • Errors are values. Return error as the last result, wrap with fmt.Errorf("...: %w", err), and test with errors.Is and errors.As. panic is for programmer errors, and recover works only inside a deferred function.
Go Typed nil, shared slices and defer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Rust: what is ownership?

Short answer: Every value in Rust has exactly one owner. When the owner goes out of scope the value is dropped (its memory freed), so there is no garbage collector and no manual free. Assigning or passing a value to a function moves ownership; the old variable can no longer be used. Types that are cheap bitwise copies (integers, bool, char) implement Copy and are copied instead of moved.

The compiler enforces this, and the error is one of the most famous in the language. This is read-only output from the real compiler for a program that uses a String after moving it:

Rust
let s = String::from("hello");
let t = s;
println!("{}", s);
TEXT
error[E0382]: borrow of moved value: `s`
 --> main.rs:4:20
  |
2 |     let s = String::from("hello");
  |         - move occurs because `s` has type `String`, which does not implement the `Copy` trait
3 |     let t = s;
  |             - value moved here
4 |     println!("{}", s);
  |                    ^ value borrowed here after move

What are borrowing and lifetimes?

Short answer: Instead of moving a value you can borrow it with a reference. The rule is: at any moment you may have any number of shared references (&T) or exactly one mutable reference (&mut T), never both. This rule, checked at compile time, is what removes data races and iterator invalidation. A lifetime is the region of code where a reference is valid; the compiler checks that a reference never outlives the value it points to. You write lifetime annotations ('a) only when a function returns a reference and the compiler cannot work out which input it came from.

Rust Moves, borrows and a lifetime annotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you moved the v.push(4) line above println!("first = {}", first), the compiler would refuse: first is a shared borrow still in use while push needs a mutable one.

How does Rust handle errors and absent values?

Short answer: There are no exceptions and no null. A value that might be missing is an Option<T> (Some(x) or None); an operation that might fail returns Result<T, E> (Ok(x) or Err(e)). The compiler forces you to handle both cases, usually with match, and the ? operator returns early with the error, converting it as needed. unwrap() panics on failure, so use it only in tests and examples.

Traits are Rust's interfaces: they define shared behaviour with optional default methods. Generics with a trait bound (T: Shape) are resolved at compile time (static dispatch, no overhead). A trait object (Box<dyn Shape>) uses a vtable at run time (dynamic dispatch) and lets one Vec hold different types.

Rust Result, Option and trait objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

How does Rust make threads safe?

Short answer: Two marker traits do the work. Send means a value can be moved to another thread; Sync means a shared reference to it can be used from several threads. The compiler refuses to spawn a thread with a non-Send value such as Rc<T> (a non-atomic reference counter). The tools are Arc<T> (atomic reference counting, for shared ownership across threads), Mutex<T> (the data is only reachable through the lock, so you cannot forget it), and channels from std::sync::mpsc.

Rust Arc and Mutex, and a channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Compare with Go: Go lets you write the racy counter and finds the problem at run time with -race; Rust will not compile the racy version at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does closing a channel in Go signal?

    Closing says there will be no more sends. A range loop over the channel ends once it is drained. Only the sender should close it.
  2. 2. A function returns a typed nil *MyErr as an error interface. What does err == nil give in the caller?

    An interface equals nil only when both its type and value are empty. A typed nil pointer makes the interface non-nil.
  3. 3. What happens when a String is assigned to another variable in Rust (let t = s;)?

    String does not implement Copy, so the assignment moves ownership. Using s afterwards is a compile error.
  4. 4. Which borrow combination is allowed at the same time in Rust?

    Either many shared references or one mutable reference. The compiler checks this, preventing data races.
  5. 5. Why can't an Rc<T> be sent to another thread in Rust?

    Rc updates its count without atomic operations, so sharing it across threads would race. Arc uses atomic counting and is Send.

Summary

  • Goroutines are cheap, runtime-scheduled functions; coordinate them with channels, WaitGroup, Mutex and select.
  • A typed nil inside an interface is non-nil; slices share storage until append reallocates; defer is last-in-first-out.
  • Rust gives every value one owner; assignment moves, Copy types are copied, drop frees at scope end.
  • Borrow rule: many &T or one &mut T; lifetimes prove references do not outlive their data.
  • Option and Result replace null and exceptions; ? propagates errors.
  • Send, Sync, Arc and Mutex make threading safe at compile time.

Next: C# and .NET Interview Questions.