Golang Interview Questions for Experienced
16. How does ‘Slice’ work in GoLang?
Slice is one data type in GoLang. It is a simple and lightweight data structure used for storing homogeneous data of variable length. There are three components of Slice:
It points to the first element of the array accessible using Slice.
It is the count of the total number of elements in the slice. Length can be equal to or less than the capacity.
It gives the maximum number of elements present in a Slice. It can be equal to or more than the capacity.
17. Explain various aspects of Go Interfaces.
Go Interfaces are a little different from other languages’ interfaces. They have a pre-defined set of method signatures. They are abstract; therefore, we cannot find an instance of any of them.
An interface acts as two things:
- Custom Types
- Collection of Method Signatures
18. Give the syntax of the ‘for’ loop in GoLang?
The syntax of the ‘for’ loop in GoLang is given below.
for [condition | (init; condition; increment) | Range]
{
statements;
}
For Example,
package main
import “fmt”
func main(){
for i := 2; i <= 10; i+=2 {
fmt.Print(i)
}
}
Output:
1 2 3 4 5 6 7 8 9 10
19. Describe the CGo keyword in GoLang.
The CGo keyword of GoLang permits Go packages to invite C code. Suppose you have a C file with really impressive and unique features. You want to use this file in your Go code. So, CGo allows you to merge C and Go files into a new Go package.
20. Which data type would you use for concurrent data access? Why?
Channels are considered safer for concurrent data access. This is because they have a blocking and locking mechanism that doesn’t permit the goroutine to share its memory. In the presence of several threads, its blocking and locking mechanism becomes even more robust.
21. How would you explain GoLang Methods?
We already know that GoLang works with methods but not classes. These methods are similar to the functions in other languages. The difference is that the Go Methods contain a receiver argument. The GoLang methods also determine the properties of the receiver.
GoLang Methods are also known as receiver functions. These methods present a real-world and better concept.
22. Explain GoLang pointers in detail. Give its advantages.
Go Pointers are special variables used to store addresses of other variables. There are two types of operators that Pointer supports.
The dereferencing or * operator is used to access the address’s value of the variable stored in the pointer.
The address or & operator is used to return the address’s value of the variable stored in the pointer.
Some of its advantages are listed below.
- Increases the edge cases’ success rate.
- Permits functions to directly mutate the passed values.
- Helps mention the lack of values.
23. Write a GoLang code to compare two slices.
The GoLang code to compare the two slices is given below.
package main
import
(
"bytes"
"fmt"
)
func main(){
x1 := []byte{'C', 'O', 'D', 'I', 'N', 'G'}
x2 := []byte{'N', 'I', 'N', 'J', 'A', 'S'}
output := bytes.Compare(x1, x2)
if output == 0 {
fmt.Println("Equal")
}
else {
fmt.Println("Not Equal")
}
}
Output:
Not Equal
24. Explain Shadowing using an example.
Shadowing is when a variable overrides another variable in a particular scope. This situation usually occurs when a variable with the same name and data type is declared in an inner and outer scope.
You can use the example below for your reference.
var brands = 2
type chocolate struct{
name string
flavor string
}
chocolates := [{
name : “DairyMilk”,
flavor : “Oreo”
},
{
name : “DairyMilk”,
flavor : “RedVelvet”
}]
func countchocolate(){
for i := 0; i < brands; i++{
if chocolate[i].flavour == “Oreo” {
brands += 1
fmt.Println(brands)
}
}
}
In this example variable ‘name’ in the outer scope shadows the variable ‘name’ in the inner scope.
25. Write a GoLang program to print the xth Fibonacci series.
Use the following GoLang code to print the xth Fibonacci series.
package main
import "fmt"
func Fib(x int) int {
if x < 2 {
return x
}
return Fib(x-1) + Fib(x-2)
}
func main() {
fmt.Println(Fib(10))
}
Output:
55
26. How do you copy the value of the Map variable in GoLang?
You can copy the values of a Map variable in GoLang by traversing its keys. The simplest way to copy a map in GoLang is given below.
x := map[string]int{“A” : 1, “B” : 2}
y := make(map[string]int)
for key, value := range a{
b[key] = value
}
27. Give a function that reverses a slice of integers.
Use the GoLang function code to reverse a slice of integers.
func reverse(sl []int){
for x, y := 0, len(sl)-1; x < y; x, y = x+1, y+1{
sl[x], sl[y] = sl[y], sl[x]
}
}
func main(){
i := []int{10, 20, 30, 40, 50}
reverse(i)
fmt.Println(i)
}
Output:
50 40 30 20 10
28. What is constants? Explain its types.
By their name, it is somewhere clear that constants are some constant values given to a variable. These variables do not change their values in a defined scope. There are two types of constants.
A constant is said to be untyped till it is given a type ‘typed’ explicitly. to avoid GoLang’s strong type system temporarily.
For Example,
const x=0
var myFloat32 f=7.5
A constant is said to be typed when you mention the keyword ‘typed’ along with the variable. That is, you declare its type explicitly. This type strips off the flexibility that comes with untyped constants.
const typedInt x=0
29. Do you have the option to return multiple values from a function in GoLang?
Yes, a developer can return multiple values from any GoLang function. You must use comma-separated values with the return statement and assign them to multiple variables.
Use the following GoLang code for your reference.
package main
import (
“fmt”
)
func reverseV(x,y string)(string, string){
return y,x
}
func main(){
v1, v2 := reverseV(“coding”,”ninjas”)
fmt.Println(v1,v2)
}
Output:
ninjas coding
30. How are errors handled in GoLang?
In GoLang, errors are any interface type implementing the Error() method. Here, you do not have try or catch methods as in other languages. Errors are returned as normal values.
The syntax to create an error interface is given below.
type name interface{
Error() int
}
31. How will you copy the values of a slice in GoLang?
Copying a slice in GoLang is very easy. You can use the built-in method ‘copy()’.
Use the example below for your reference.
s1 := []int{10, 20, 30}
s2 := []int{40, 50, 60}
s3 := s1
copy(s1, s2)
fmt.Println(s1, s2, s3)
Output:
[40 50 60] [40 50 60] [40 50 60]
Golang Programs
32. Write a Golang program to check if a number is prime.
package main
import (
"fmt"
"math"
)
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
func main() {
var num int
fmt.Print("Enter number: ")
fmt.Scan(&num)
if isPrime(num) {
fmt.Println(num, "is prime number.")
} else {
fmt.Println(num, "is not prime number.")
}
}
Output:
Enter number: 7
9 is prime number.
33. Write a Golang program to find the factorial of a number.
package main
import "fmt"
func facto(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
func main() {
var n int
fmt.Print("Enter number: ")
fmt.Scan(&n)
fmt.Println("Factorial of", n, "is", facto(n))
}
Output:
Enter number: 5
Factorial of 5 is 120
34. Write a Golang program to reverse a string.
package main
import "fmt"
func rvrseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func main() {
var s string
fmt.Print("Enter string: ")
fmt.Scan(&s)
fmt.Println("Reversed string is:", rvrseString(s))
}
Output:
Enter string: Rohit
Reversed string is: tihor
35. Write a Golang program to find the largest element in an array.
package main
import "fmt"
func largestElmnt(a []int) int {
largest := a[0]
for _, value := range a {
if value > largest {
largest = value
}
}
return largest
}
func main() {
a := []int{10, 24, 99, 12, 25, 56, 89}
fmt.Println("Largest element in the array is:", largestElmnt(a))
}
Output:
Largest element in the array is: 99
36. Write a Golang program to find the sum of digits of a number.
package main
import "fmt"
func sumDigit(n int) int {
sum := 0
for n != 0 {
sum += n % 10
n /= 10
}
return sum
}
func main() {
var n int
fmt.Print("Enter number: ")
fmt.Scan(&n)
fmt.Println("Sum of digits:", sumDigit(n))
}
Output:
Enter number: 1235
Sum of digits: 11
37. Write a Golang program to generate the Fibonacci series up to n terms.
package main
import "fmt"
func fibo(n int) {
a, b := 0, 1
for i := 0; i < n; i++ {
fmt.Print(a, " ")
a, b = b, a+b
}
}
func main() {
var n int
fmt.Print("Enter the number: ")
fmt.Scan(&n)
fmt.Println("Fibonacci series:")
fibo(n)
}
Output:
Enter the number: 7
Fibonacci series:
0 1 1 2 3 5 8
38. Write a Golang program to check if a number is an Armstrong number.
package main
import (
"fmt"
"math"
)
func armstrongNum(n int) bool {
sum, temp := 0, n
numDigits := len(fmt.Sprintf("%d", n))
for temp != 0 {
digit := temp % 10
sum += int(math.Pow(float64(digit), float64(numDigits)))
temp /= 10
}
return sum == n
}
func main() {
var n int
fmt.Print("Enter a number: ")
fmt.Scan(&n)
if armstrongNum(n) {
fmt.Println(n, "is an Armstrong number.")
} else {
fmt.Println(n, "is not an Armstrong number.")
}
}
Output:
Enter a number: 153
153 is an Armstrong number.
39. Write a Golang program to check if a string is a palindrome.
package main
import "fmt"
func palindromeString(s string) bool {
for i := 0; i < len(s)/2; i++ {
if s[i] != s[len(s)-1-i] {
return false
}
}
return true
}
func main() {
var s string
fmt.Print("Enter a string: ")
fmt.Scan(&s)
if palindromeString(s) {
fmt.Println(s, "is a palindrome.")
} else {
fmt.Println(s, "is not a palindrome.")
}
}
Output:
Enter a string: rohit
rohit is not a palindrome.
40. Write a Golang program to swap two numbers without using a temporary variable.
package main
import "fmt"
func main() {
var a, b int
fmt.Print("Enter two numbers: ")
fmt.Scan(&a, &b)
fmt.Println("Before swapping: a =", a, "b =", b)
a, b = b, a
fmt.Println("After swapping: a =", a, "b =", b)
}
Output:
Enter two numbers: 5 10
Before swapping: a = 5 b = 10
After swapping: a = 10 b = 5
Golang MCQ
1. What is the output of the following code?
package main
import "fmt"
func main() {
x := 555
fmt.Println(x)
}
A) 555
B) 0
C) Compilation Error
D) Runtime Error
Answer: A) 555
2. Which of the following is correct about Go arrays?
A) Arrays are immutable.
B) Arrays are dynamic in size.
C) Arrays are reference types.
D) Arrays have a fixed size.
Answer: D) Arrays have a fixed size.
3. Which keyword is used to define a structure in Go?
A) struct
B) class
C) type
D) interface
Answer: A) struct
4. How do you declare a constant in Go?
A) var
B) const
C) define
D) let
Answer: B) const
5. What does the defer statement do in Go?
A) Executes a function immediately
B) Executes a function after the surrounding function returns
C) Skips the execution of a function
D) None of the above
Answer: B) Executes a function after the surrounding function returns
6. Which of the following is the correct way to import multiple packages in Go?
A) import "fmt", "math"
B) import ("fmt"; "math")
C) import "fmt" "math"
D) import ("fmt", "math")
Answer: D) import ("fmt", "math")
7. What is the zero value for an int type in Go?
A) -1
B) 0
C) 1
D) nil
Answer: B) 0
8. How do you create a new Goroutine in Go?
A) Using the thread keyword
B) Using the go keyword
C) Using the routine keyword
D) Using the func keyword
Answer: B) Using the go keyword
9. Which of the following is true about slices in Go?
A) Slices are immutable.
B) Slices are dynamic in size.
C) Slices are passed by value.
D) Slices have a fixed size.
Answer: B) Slices are dynamic in size.
10. How do you handle errors in Go?
A) Using try-catch blocks
B) Using panic and recover
C) Returning an error value
D) Both B and C
Answer: D) Both B and C
Frequently Asked Questions
How do I prepare for a Golang interview?
You start preparing for a Golang interview by mastering the core concepts, practice coding challenges, understand concurrency, and be familiar with common libraries. Explore real-world Golang projects to enhance practical knowledge.
What is Golang used for?
Golang is used for building scalable, concurrent systems. It's efficient for web development, networking tools, distributed systems, and cloud-based applications due to its simplicity and performance.
What are the several built in support in go?
Go boasts built-in support for concurrency with goroutines and channels, efficient garbage collection, a robust standard library, and features like slices and maps for streamlined data manipulation.
Why is go often called a post oop language?
Go is considered post-OOP because it minimizes reliance on classical object-oriented programming (OOP) principles, favoring composition over inheritance and emphasizing simplicity and efficiency in code design.
Conclusion
We hope you have gained insights on Golang Interview Questions through this article. This will help you excel in your interviews and enhance your knowledge of Golang. These Golang Interview Questions and answers suit freshers and experienced candidates.
This set of Golang interview questions will help you in interviews and increase your understanding of the same.
Here are some of the interview questions on some of the famous topics:
- SQL Query Interview Questions
-
SAP FICO Interview Questions
- Html interview questions
- C++ Interview Questions
- Excel Interview Questions
- MVC Interview Questions
For peeps who want to grasp more knowledge other than Golang Interview Questions, that is, DBMS, Operating System, System Design, and DSA, refer to the respective links. Make sure that you enroll in the courses we provide, take mock tests, solve problems available, and interview puzzles. Also, you can pay attention to interview stuff- interview experiences and an interview bundle for placement preparations. Do upvote our blog to help other ninjas grow.
Happy Coding!