Fundamentals Flashcards
What is the default value of an uninitialized variable in Go?
The zero value, which depends on the type (e.g., 0 for integers, “” for strings, false for booleans).
How do you declare a variable in Go without initializing it?
var x int (this sets x to the zero value of int, which is 0).
What is the difference between := and var in Go?
:= is used for short variable declarations and can only be used inside functions, while var can be used both inside and outside functions.
What does the defer keyword do in Go?
It defers the execution of a function until the surrounding function returns.
Explain how slices work in Go.
A slice is a dynamically-sized, flexible view into the elements of an array. It references a part or all of an underlying array.
How do you handle errors in Go?
Errors are handled using a return value, typically the last value returned by a function, and are checked with an if err != nil block.
What is a Goroutine?
A Goroutine is a lightweight thread managed by the Go runtime, allowing concurrent execution of functions.
How do you start a new Goroutine?
By prefixing a function call with the go keyword, e.g., go myFunction().
How does Go manage memory?
Go has automatic memory management with garbage collection, freeing memory that is no longer referenced.
What is a channel in Go?
A channel is a typed conduit through which Goroutines communicate with each other. Channels synchronize Goroutines’ execution.
How do you send data to a channel?
Using the syntax ch <- value, where ch is the channel and value is the data to send.
What is the purpose of the select statement in Go?
select allows a Goroutine to wait on multiple communication operations on channels and execute whichever is ready first.
Can Go support inheritance?
No, Go does not support traditional inheritance but achieves similar behavior through composition using interfaces and structs.
How are interfaces defined in Go?
Interfaces are defined as a set of method signatures. Any type that implements these methods satisfies the interface.
What is a pointer in Go, and how do you declare one?
A pointer holds the memory address of a variable. It is declared with an asterisk (*), e.g., var p *int.
How do you retrieve the value a pointer is pointing to in Go?
By dereferencing the pointer using the asterisk (*), e.g., *p retrieves the value stored at the memory address p points to.
What is the difference between a slice and an array in Go?
An array has a fixed size defined at declaration, while a slice is a dynamically sized view into an array that can grow or shrink as needed.
How do you create a slice from an array in Go?
By specifying a range, e.g., arr[1:4] creates a slice from the array arr containing elements at indices 1, 2, and 3.
How do you append elements to a slice in Go?
Using the built-in append function, e.g., slice = append(slice, elem)
What are Go’s built-in data types?
Basic types include int, float64, string, bool, and composite types include array, slice, struct, map, interface, and channel.
What is the difference between make and new in Go?
make is used for initializing slices, maps, and channels, while new allocates memory but does not initialize the value.
How do you define a struct in Go?
A struct is defined using the type keyword, followed by the struct name and fields.
Example:
type Person struct { Name string Age int }
How do you instantiate and use a struct in Go?
p := Person{Name: "John", Age: 30} fmt.Println(p.Name, p.Age)
What does the go fmt tool do?
go fmt formats Go source code according to the standard style guidelines.
What are the ways to declare constants in Go?
Constants are declared using the const keyword, and their values must be assigned at compile-time.
const Pi = 3.14
What is the purpose of the iota keyword in Go?
iota is used to simplify constant declarations. It is reset to 0 at the start of each const block and increments automatically.
const ( A = iota B = iota )
What is the purpose of the panic function in Go?
panic is used to stop the execution of a program when something unexpected happens. It typically signals unrecoverable errors.
How do you recover from a panic in Go?
By using the recover function inside a deferred function. recover can catch a panic and prevent the program from crashing.
How do you handle multiple return values in Go?
Go functions can return multiple values. They are returned as a comma-separated list.
func divide(a, b int) (int, error) { if b == 0 { return 0, fmt.Errorf("division by zero") } return a / b, nil }
What is the difference between passing by value and passing by reference in Go?
Passing by value creates a copy of the data and does not affect the original variable, while passing by reference (using pointers) allows the function to modify the original variable.
How do you create a map in Go?
A map is created using the make function or a map literal.
m := make(map[string]int) m["key"] = 10
How do you check if a key exists in a Go map?
By using the value-comma-ok idiom.
val, ok := m["key"] if ok { fmt.Println("Key exists") }
How do you declare a function in Go?
Functions are declared using the func keyword followed by the name, parameters, and return type.
func add(a int, b int) int { return a + b }
What is a method in Go, and how is it different from a function?
A method is a function with a receiver, which is the type it is associated with.
func (p Person) Greet() string { return "Hello, " + p.Name }
How do you define an anonymous function in Go?
An anonymous function is a function without a name.
func() { fmt.Println("Anonymous function") }()
How do you define a function that returns another function in Go?
You return the function type as part of the return signature.
func adder(a int) func(int) int { return func(b int) int { return a + b } }
What are variadic functions in Go?
A variadic function can accept any number of arguments of the same type.
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total }
How do you convert a slice into variadic arguments in Go?
By using the … operator.
nums := []int{1, 2, 3} sum(nums...)
How do you use the range keyword with slices in Go?
range is used to iterate over elements in a slice.
for i, v := range slice { fmt.Println(i, v) }
How do you prevent race conditions when working with Goroutines in Go?
Use channels or the sync.Mutex to synchronize access to shared variables between Goroutines.
What does the sync.WaitGroup do in Go?
It is used to wait for a collection of Goroutines to finish executing.
var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() // goroutine logic }() wg.Wait()
What are Go’s built-in control flow statements?
Go includes standard control flow statements like if, for, switch, and select.
How does Go handle switch statements differently than other languages?
Go’s switch does not require explicit break statements, as each case is automatically terminated unless the fallthrough keyword is used.
What are Go’s looping constructs?
Go only has the for loop, which can be used in various ways:
Traditional loop: for i := 0; i < 10; i++ {}
While loop: for i < 10 {}
Infinite loop: for {}
What is the difference between break and continue in Go loops?
break exits the loop entirely, while continue skips to the next iteration.
How do you handle concurrent reads and writes to a map in Go?
Go’s maps are not thread-safe, so you should use a sync.Mutex or sync.RWMutex to handle concurrent access to maps.
How do you check the type of an interface at runtime in Go?
By using a type assertion or a type switch.
value, ok := interfaceVar.(string)
What does the blank identifier (_) do in Go?
The blank identifier is used to discard a value that you don’t need.
How do you copy one slice to another in Go?
By using the copy function.copy(dst, src)
Can a slice hold different types of data in Go?
No, slices in Go are homogenous. They can only hold elements of the same type. However, you can use a slice of type interface{} to store different types.