Go Programming Questions and Answers
1. Basic Concepts of Go Language
a) What are nested structures?
Nested structures allow one struct to be embedded within another.
They help in organizing complex data models.
The inner struct can be accessed using dot notation.
Example:
type Address struct {
City, State string
}
type Employee struct {
Name string
Age int
Address Address
}
b) What is a method in Go programming?
A method is a function with a receiver.
It operates on a specific type (struct or other custom types).
Example:
type Person struct {
Name string
}
func (p Person) Greet() {
fmt.Println("Hello,", p.Name)
}
c) What is the use of wait Groups?
sync.WaitGroup is used to wait for multiple goroutines to finish execution.
Methods: Add(n), Done(), Wait().
Example:
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("Hello")
}()
wg.Wait()
d) Define a package.
A package in Go is a collection of related Go files.
Encourages modularity and reusability.
Example:
package mathutil
func Add(a, b int) int {
return a + b
}
e) What are blank imports?
Blank imports ( _ "package" ) import a package only for its initialization.
Example:
import _ "database/sql"
2. Go Programming Advantages
a) Three advantages of Go programming language:
1. Fast Compilation
2. Efficient Concurrency
3. Garbage Collection
b) Function returning multiple values
Go functions can return multiple values.
Example:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
c) Different types of arrays in Go
1. Single-dimensional array
2. Multi-dimensional array
3. Slices (dynamic array-like structure)
Example:
arr := [3]int{1, 2, 3}
d) Describe an Interface in Go
An interface is a type that specifies method signatures.
Used for polymorphism and abstraction.
Example:
type Shape interface {
Area() float64
}
e) Compare Concurrency and Parallelism
Concurrency: Multiple tasks start but may not run simultaneously.
Parallelism: Multiple tasks run simultaneously.
f) How package names are imported
import "fmt" - Imports a standard library package.
import mypkg "github.com/user/mypkg" - Imports with alias.