1What are the differences between Go rune literals, interpreted string literals and raw string literals?
A rune literal uses single quotes, such as 'A' or '\n', and denotes one Unicode code-point integer constant; rune is an alias for int32. An interpreted string literal uses double quotes and processes escapes such as \n, \t and Unicode escapes. A raw string literal uses backticks, can span lines and treats backslashes literally; it cannot contain a backtick, and carriage-return characters are discarded from its value. Both string forms produce strings, not rune arrays. Go strings are immutable byte sequences and can contain bytes that are not valid UTF-8. len(s) counts bytes, while ranging over a string decodes runes, so a visible character may require several bytes and even several code points. I would choose raw literals for readable multiline text or patterns and interpreted literals when escapes or embedded backticks are needed.
2How does Go handle equality for structs and what happens when a struct contains incomparable fields?
Struct values in Go can be compared with `==` and `!=` only when every field in the struct is comparable. Equality compares corresponding fields using each field's own equality rule. If a struct contains an incomparable field such as a slice, map, or function, the struct type is not comparable, and comparing two values of that struct type with `==` is a compile-time error. For such structs, use custom comparison logic or an appropriate deep-equality helper, especially in tests.
package main
import "fmt"
type UserID struct {
Name string
Age int
}
type UserProfile struct {
Name string
Tags []string
}
func main() {
a := UserID{"Ann", 30}
b := UserID{"Ann", 30}
fmt.Println(a == b)
x := UserProfile{Name: "Ann", Tags: []string{"go"}}
y := UserProfile{Name: "Ann", Tags: []string{"go"}}
_, _ = x, y
// fmt.Println(x == y) // compile error: struct containing []string cannot be compared
}
3Explain string immutability in Go and the relationship between string, []byte, bytes.Buffer, and strings.Builder.
A Go `string` is an immutable sequence of bytes, often UTF-8 text but not required to be valid UTF-8. You cannot modify a string in place; to change contents you typically convert to `[]byte` for byte-level edits or `[]rune` for code-point edits, then convert back. Normal conversions between `string` and `[]byte` copy data and may allocate, so repeated conversions or repeated concatenation in loops can be expensive. `strings.Builder` is optimized for efficiently building strings, while `bytes.Buffer` is a mutable byte buffer useful for byte-oriented data and I/O and can also produce a string.
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {
var sb strings.Builder
sb.WriteString("hello")
sb.WriteByte(' ')
sb.WriteString("world")
fmt.Println(sb.String())
var buf bytes.Buffer
buf.Write([]byte{0x48, 0x69})
buf.WriteByte('!')
fmt.Println(buf.String())
s := "cat"
b := []byte(s) // normally copies
b[0] = 'b'
fmt.Println(s, string(b))
}
4How do pointers work in Go, and what operations are intentionally disallowed compared to C?
A Go pointer is a typed value that holds the address of another value, such as *int pointing to an int. Use &x to take a value's address and *p to dereference a pointer to read or write the pointed-to value. Passing or storing a pointer lets multiple places observe or mutate the same underlying value, and a pointer can be nil. Unlike C, safe Go intentionally disallows pointer arithmetic and arbitrary raw-address manipulation; low-level exceptions require the unsafe package.
package main
import "fmt"
func inc(p *int) {
*p = *p + 1
}
func main() {
x := 10
p := &x
inc(p)
fmt.Println(x)
}
5Explain how constants and iota work in Go, including typed versus untyped constants.
Go constants are compile-time values: boolean, string, or numeric. A typed constant has a specific type. An untyped constant has no fixed concrete type until it is used in a typed context, and numeric untyped constants are represented exactly/high precision until then; the value must be representable in the chosen type. `iota` is a predeclared identifier used in `const` declarations: it starts at 0 in each const block and increments for each constant specification, making it useful for enum-like constants and bit flags.
type Status int
const (
StatusPending Status = iota // 0, typed Status
StatusActive // 1, same expression/type repeated
StatusClosed // 2
)
const big = 1 << 100 // untyped integer constant with high precision
var x int64 = 42 // untyped 42 can become int64
// var y int64 = big // compile error: not representable as int64
6How do explicit conversions work in Go, and why does the language avoid many implicit conversions?
Go generally requires explicit conversions using `T(x)` when changing a value’s type, such as `int64(i)` or `MyID(n)`. This keeps type changes visible and avoids surprising implicit numeric, boolean, or string conversions. Conversions are only allowed by Go’s conversion rules and may change the value, for example through integer overflow/truncation, float-to-int truncation toward zero, or precision loss. Untyped constants are more flexible: they can be used in a typed context if the constant value is representable in that type.
var x int64 = 300
var y int8 = int8(x) // explicit conversion; value changes
var f float64 = 3.9
var i int = int(f) // truncates toward zero
const c = 42
var n int32 = c // ok: untyped constant is representable as int32
7How do you initialize a Go map, and how do you distinguish a missing key from a stored zero value?
I can create a writable map with m := make(map[string]int), optionally supplying a capacity hint, or with a literal such as map[string]int{"a": 0}. A declaration var m map[string]int leaves a nil map: reads return the value type's zero value and delete is harmless, but assigning an entry panics until the map is initialized. To distinguish absence from a stored zero, use v, ok := m["a"]; ok is true even though v is zero for the literal above, and false for a missing key. Keys must be comparable. Iteration order is unspecified, so sort keys if stable output is required. Ordinary maps do not support unsynchronized concurrent reads and writes; protect shared mutation with a mutex or choose a suitable concurrent design. The capacity hint is not a fixed size limit.
8How does Go's map type behave regarding key types, missing keys, nil maps, and iteration order?
Go map key types must be comparable; slices, maps, and functions cannot be used directly as keys. Looking up a key that is not present returns the element type's zero value, so the comma-ok form (`v, ok := m[k]`) is used to distinguish absence from a present zero value. A nil map can be read from and ranged over, but assigning to it panics; initialize it before writing. Map iteration order is unspecified and code must not depend on it.
package main
import "fmt"
func main() {
counts := map[string]int{"a": 0, "b": 2}
fmt.Println(counts["missing"]) // zero value for int
v, ok := counts["a"]
fmt.Println(v, ok) // present even though value is zero
var m map[string]int
fmt.Println(m["x"]) // read from nil map is OK
// m["x"] = 1 // panic: assignment to entry in nil map
m = make(map[string]int)
m["x"] = 1
for k, v := range counts {
fmt.Println(k, v) // order is not guaranteed
}
}
9When should you pass a struct or other value by value versus by pointer in Go?
Pass by value when the value is small, read-only for the call, or you want independent copy semantics. Pass by pointer when the function must mutate the caller's value, copying would be expensive, the type should not be copied, or nil/shared identity is part of the API. Do not assume pointers are always faster: they can add aliasing, heap escapes, GC work, and less cache-friendly access. Prefer clear semantics first and benchmark performance-sensitive choices.
package main
import "fmt"
type Counter struct{ N int }
func Read(c Counter) int {
c.N++
return c.N
}
func Inc(c *Counter) {
c.N++
}
func main() {
c := Counter{N: 5}
fmt.Println(Read(c), c.N)
Inc(&c)
fmt.Println(c.N)
}
10What are GOROOT and GOPATH used for in a module-based Go project, and how can a program read its runtime environment?
GOROOT identifies the Go toolchain installation tree and is normally discovered by the go command rather than manually set. GOPATH is no longer the required location for module-based project source: a project can live elsewhere and uses go.mod to define its module. GOPATH still supplies defaults for the module cache and installed command binaries, with GOMODCACHE and GOBIN able to override those locations. I would inspect tool settings with go env rather than assume environment variables are explicitly exported. Inside a running program, os.Getenv reads a value and os.LookupEnv distinguishes an unset variable from an explicitly empty one; runtime.GOOS, GOARCH and Version provide runtime/build platform information. A deployed binary may run without a Go installation, so toolchain paths are not reliable application-resource paths. I would avoid dumping the full environment into logs because it can contain credentials.
11What happens when Go code sends into a buffered channel that has reached capacity?
When a buffered channel is full, a send waits until capacity becomes available, normally because a receiver consumes a value. It blocks that goroutine, not necessarily all other goroutines, and does not automatically drop or overwrite data. This is backpressure; if nothing can receive, the goroutine may remain stuck. Use select with a send case and a context cancellation/deadline case to bound the wait, or a default case for an explicit nonblocking fallback such as rejection or dropping according to policy. Checking len(ch) before sending is not a synchronization guarantee because another goroutine can change occupancy. Sending to a closed channel panics, while sending to a nil channel blocks indefinitely; nil cases in select are disabled. Channel-closing ownership must therefore be coordinated separately from capacity management.
12Describe the semantics of range over arrays, slices, maps, strings, and channels.
`range` iterates according to the operand type. Over an array or slice it yields an index and an element value; the element value is a copy, so assigning to it does not modify the collection. Ranging over an array value copies the array for iteration, while ranging over a slice uses the slice header and indexes the underlying array. Over a map it yields key and value in an unspecified order, and the value is a copy. Over a string it yields the byte index and decoded Unicode code point (`rune`), not a rune-position index. Over a channel it receives values until the channel is closed and drained; a nil channel range blocks forever.
package main
import "fmt"
func main() {
xs := []int{1, 2, 3}
for _, v := range xs {
v *= 10 // modifies only the copy
}
fmt.Println(xs)
for i := range xs {
xs[i] *= 10 // modifies the slice element
}
fmt.Println(xs)
}
13What is the difference between value receivers and pointer receivers, and how do receiver choices affect mutability, copying, and interface satisfaction?
A value receiver method receives a copy of the receiver, so it is suitable for read-only behavior and small immutable-style types; changes to the receiver copy are not visible to the caller. A pointer receiver method receives a copy of a pointer to the receiver, so it can mutate the original and avoid copying large or should-not-copy values. Receiver choice affects method sets: methods with value receivers are in the method set of both T and *T, while methods with pointer receivers are only in the method set of *T. Therefore, an interface requiring a pointer-receiver method is satisfied by *T, not T, even though an addressable T value may call the method using ordinary method-call syntax.
package main
import "fmt"
type Counter struct{ N int }
func (c Counter) AddValue() { c.N++ }
func (c *Counter) AddPointer() { c.N++ }
func main() {
c := Counter{N: 1}
c.AddValue()
fmt.Println(c.N)
c.AddPointer() // compiler rewrites to (&c).AddPointer() because c is addressable
fmt.Println(c.N)
}
14Describe how interfaces work in Go and what it means for a type to satisfy an interface implicitly.
A Go interface defines a set of required methods. A concrete type satisfies an interface implicitly when its method set contains those methods; there is no implements declaration. An interface variable can hold a concrete dynamic value whose type satisfies the interface, and interface method calls dispatch to that dynamic value's implementation. The empty interface, written interface{} or usually any, has no required methods, so every type satisfies it. Whether T, *T, or both satisfy an interface depends on their method sets and receiver choices.
package main
import "fmt"
type Greeter interface {
Greet() string
}
type User struct{ Name string }
func (u User) Greet() string { return "hello, " + u.Name }
func Say(g Greeter) {
fmt.Println(g.Greet())
}
func main() {
Say(User{Name: "Ana"}) // no 'implements Greeter' declaration needed
}
15How do type assertions and type switches work with interface values?
A type assertion checks the dynamic value stored in an interface: `v := x.(T)` succeeds if the interface value’s dynamic type is `T`, or if `T` is an interface implemented by the dynamic value. The single-result form panics if it fails. The comma-ok form, `v, ok := x.(T)`, reports success without panicking. A type switch, `switch v := x.(type)`, branches based on the interface value’s dynamic type, with `v` typed according to the matched case.
func describe(x any) string {
if s, ok := x.(string); ok {
return "string: " + s
}
switch v := x.(type) {
case int:
return fmt.Sprintf("int: %d", v)
case fmt.Stringer:
return "stringer: " + v.String()
case nil:
return "nil interface"
default:
return fmt.Sprintf("unknown %T", v)
}
}