ADVERTISEMENT
ADVERTISEMENT

Go Language Interview Questions

This section contains the list of top frequently asked Go programming interview questions and answers. These questions are designed by the experts and tested well. Each question has its answer with the explanation, syntax, and example where needed. Practice & learn these Golang Interview Questions to enhance the skill of the Go programming language.

Golang Interview Questions

List of Golang Interview Questions

Here is the list of top 50 Golang interview questions and answers,

1) What is Go programming language?

Go language is an open-source programming language that makes it easy to build simple, reliable, and efficient software. The Go language is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. The Go language is syntactically similar to the C programming language, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.


2) Why should one use Go programming language?

One should use the Go programming language because its features like its an open-source programming language, that makes it easy to build simple, reliable, and efficient software.


3) Who developed Go language?

Go programming language is designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson.


4) What are the differences between Golang and Java?

Java programming language is the older and more widely used programming language. So, it has a larger community.

  • Java is an object-oriented language.
  • Virtual machine
  • Bigger community
  • Slower

While Go language is newer but it supports concurrency, fast, more readable.

  • Go is not object-oriented.
  • Go doesn't have exception handling.
  • Easy to read and understand.
  • Fast

5) What are the benefits of using Go compared to other languages?

There are the following benefits of using the Go language,

  • Open-source: Go programming language is an open-source project to make programmers more productive. So, anyone can download and experiments with the code to make it better to use.
  • Static Typing: Go programming language is statically typed and compiles the code accurately while taking care of type conversions and compatibility levels.
  • Concurrency Support: It is one of the most prime features of the Go language, Go provides easier and trackable concurrency options.
  • Readability: Go programming language is often considered more readable due to a single standard code format. Go’s syntax is familiar with C and C++ programming languages.
  • Garbage Collection: Go's garbage collection is more efficient than Java and Python.

6) What is workspace in Go language?

In the Go programming language, all programs are kept in a directory hierarchy that is called a workspace. A workspace is simply a root directory of your Go applications. A workspace contains three subdirectories at its root:

  1. src – It contains the source files organized as packages. We will write the Go applications inside the src directory.
  2. pkg – It contains Go package objects.
  3. bin – It contains executable programs.

7) What are the structures of syntax in Go?

In the Go programming language the syntaxes are specified using EBNF (Extended Backus-Naur Form)

  • Production = production name "=" [Expression]
  • Expression = Alternative {"1" Alternative}
  • Alternative = Term {Term}
  • Term = Production name token ["…." token]1 Group 1 Option 1 Repetition
  • Group = "("Expression")"
  • Option = "["Expression"]"
  • Repetition = "{"Expression"}"

8) What is GOPATH environment variable in Go language?

In Go programming language, the GOPATH environment variable determines the location of the workspace. It is the only environment variable that you have to set when developing Go code.


9) Which keyword is used to import the packages in Go language?

The import keyword is used to import the packages inside our Go language program, or it is also used for importing the package into other packages.

Consider the below syntaxes:

If there is one package, we can import it in these two ways,

import "package_name"
import (
	"package_name"
)

If there are multiple packages to be imported, we can import it by these two ways,

import "package_name_1"
import "package_name_2"
...
import (
    "package_name_1"
    "package_name_2"
    ...
)

Consider the below example – In this example, we are importing two packages.

// The main package
package main

import (
	"fmt"
	"time"
)

// The main function
func main() {
	fmt.Println("Hello, world!")
	fmt.Println("The time is", time.Now())
}

Output:

Hello, world!
The time is 2009-11-10 23:00:00 +0000 UTC m=+0.000000001

10) What is factored import statement in Go language?

The "factored" import statement groups the imports into a parenthesized.

Example:

import (
	"fmt"
    "time"
)

11) Is Go language is a case-sensitive language?

Yes, the Go language is a case-sensitive language.


12) What is the default package in Go language?

The default package in Go language is main and it should be there. It tells the Go compiler that the package should compile as an executable program instead of a shared library. And, the main() function in the package main will be the entry point of our executable program.

Consider the below example,

// The main package
package main

import (
	"fmt"
)

// The main function
func main() {
	fmt.Println("Hello, world!")
}

Output:

Hello, world!

In the above code, the first line is the comment and the second line is the main package.


13) What is the difference between := and = in Go language?

In Go programming language, the "=" is known as an assignment operator which is used to assign the value/expression to the left side variable/constant.

While ":=" is known as the short variable declaration which takes the following form,

variable_name := expression

The above statement assigns the value and determines the type of the expression. In such kind of declaration, there is no need to provide the type of the value/expression.

So, a short variable declaration (:=) required a value while declaring a new variable.

Consider the below example – demonstrating the difference between = and :=

// Go program to demonstrate the
// difference between = and :=

package main

import (
	"fmt"
)

func main() {
	// Simple declaration & assignment
	var x int = 10

	// Shorthand declaration
	y := 20

	// Printing the values and types of both
	fmt.Printf("x = %T, %v\n", x, x)
	fmt.Printf("y = %T, %v\n", y, y)
}

Output:

x = int, 10
y = int, 20

See the output – the variable x is declared and assigned using the = operator and the variable y is declared and assigned using the := operator. In the first case, the var keyword and type are required while in the second case, the var keyword and type are not required.


14) Can you declare multiple variables at once in Go?

Yes, you can declare multiple variables at once in Go.

Consider the below example,

package main

import "fmt"

func main() {
	// Declaring variables together
	var a, b, c string

	// Assigning values together
	a, b, c = "Hello", "World", "Golang"

	// Printing the types and values
	fmt.Printf("%T, %q\n", a, a)
	fmt.Printf("%T, %q\n", b, b)
	fmt.Printf("%T, %q\n", c, c)
}

Output:

string, "Hello"
string, "World"
string, "Golang"

15) What is shadowing in Go language?

In Go programming language (even in other programming languages also), the variable shadowing occurs when a variable declared within a certain scope such as decision block, method, or inner class has the same name as a variable declared in an outer scope.

Consider the below example,

// Go program to demonstrate the example
// of variable shadowing

package main

import (
	"fmt"
)

func main() {
	x := 0

	// Print the value
	fmt.Println("Before the decision block, x:", x)

	if true {
		x := 1
		x++
	}

	// Print the value
	fmt.Println("After the decision block, x:", x)
}

Output:

Before the decision block, x: 0
After the decision block, x: 0

In the above program, the statement x := 1 declares a new variable that shadows the original x throughout the scope of the if statement. So, this variable (x) declared within the if statement is known as the shadow variable.

If we want to reuse the actual variable x from the outer block, then within the if statement, write x = 1 instead.

if true {
	x = 1
	x++
}

16) What is rune in Go language?

The rune type is a datatype in the Go language, it is an alias of int32 type. It contains the Unicode code points. The unicode code point is a superset of ASCII which defines a codespace of 1,114,112 code points. Unicode version 10.0 covers 139 modern and historic scripts (including the runic alphabet, but not Klingon) as well as multiple symbol sets.


17) How to install third-party packages in Go language?

To install third-party packages: Download & install the third-party packages from the source repository by using the go get command. The go get command will fetch the packages from the source repository and install them on the GOPATH directory. And then by using the import statement, we can import those packages in our program.

Example:

go get gopkg.in/yaml.v1 

This statement will install "yaml" package.

After installing the "yaml" package, use the import statement in the program for reusing the code, as shown below:

import (        
        " gopkg.in/yaml.v1 " 
)

Consider the below example – Here, we are importing a third-party package "golang-set" from the source repository "github.com/deckarep/" and using it in the program.

package main

import (
	"fmt"
	"github.com/deckarep/golang-set"
)

func main() {
	colors := mapset.NewSet()
	colors.Add("Red")
	colors.Add("Blue")
	colors.Add("Green")

	fmt.Printf("%T, %v\n", colors, colors)
}

Output:

*mapset.threadSafeSet, Set{Red, Blue, Green}

18) What is init() function in Go language?

In Go programming language, the init() function is just like the main() function. But, the init() function does not take any argument nor return anything. The init() function is present in every package and it is caked when the package is initialized.

The init() function is declared implicitly, so we cannot reference it, we are also allowed to create more than one init() function in the same program and they execute in the order they are created.

Syntax:

func init {
   // initialization code here    
}

Example:

// Golang program to demonstrate the
// example of init() function

package main

import (
	"fmt"
)

func init() {
	fmt.Println("[1] init is called...")
}

func init() {
	fmt.Println("[2] init is called...")
}

// Main function
func main() {
	fmt.Println("Hello, world!")
}

func init() {
	fmt.Println("[3] init is called...")
}

Output:

[1] init is called...
[2] init is called...
[3] init is called...
Hello, world!

19) What is the default value of a bool variable in Go language?

The bool is a built-in data type in Go language, it can store either "true" or "false". The default value of a bool variable is "false".

Example:

// Golang program to demonstrate the
// default value of bool variable

package main

import (
	"fmt"
)

func main() {
	var x bool
	fmt.Println("Default value of bool is", x)
}

Output:

Default value of bool is false

20) What are the default values of an int, float variables in Go language?

The int, floats (float32 and float64) are the built-in data type in Go language. Their default values are 0.

Example:

// Golang program to demonstrate the default
// values of an int and floats variable

package main

import (
	"fmt"
)

func main() {
	var x int
	var y float32
	var z float64

	fmt.Println("Default value of an int is", x)
	fmt.Println("Default value of a float32 is", y)
	fmt.Println("Default value of a float64 is", z)
}

Output:

Default value of an int is 0
Default value of a float32 is 0
Default value of a float64 is 0

21) What is the default value of a string in Go language?

The string is an inbuilt data type in Go language. The default value of a string variable is an empty string.

Example:

// Golang program to demonstrate the
// default value of a string variable

package main

import "fmt"

func main() {
	var message string

	fmt.Printf("Default value is %q\n", message)
}

Output:

Default value is ""

22) What is the default value of a pointer in Go language?

A pointer stores the memory address of a value (variable). The default value of a pointer in the Go programming language is nil.

Example:

// Golang program to demonstrate the
// default value of a pointer variable

package main

import "fmt"

func main() {
	var num *int

	fmt.Println("The default value of a pointer variable:", num)
}

Output:

The default value of a pointer variable: <nil>

23) What is the default value of a structure in Go language?

A structure is a collection of primitive data types or even other structures and they inherit the default values of the types they are made out of. The default value of a structure (struct) in the Go programming language is the default value of its members.

Example:

// Golang program to demonstrate the
// default value of a structure variable

package main

import "fmt"

type Person struct {
	Name string
	Age  int
	Perc float32
}

func main() {
	var P Person

	fmt.Printf("Default value: %v\n", P)
}

Output:

Default value: { 0 0}

24) Can constants be modified in Go?

In Go language, the constants cannot be modified at runtime, they can be modified at compile-time only.

Consider the below program,

package main

import (
	"fmt"
)

func main() {
	const x int = 100
	fmt.Println(x) // Prints 100

	// Error: cannot assign to x (declared const)
	x = 200
	fmt.Println(x)
}

Output:

./prog.go:12:4: cannot assign to x (declared const)

25) How would you succinctly swap the values of two variables in Go?

The values can be swapped by using the following way,

x, y = y, x

Consider the below program,

package main

import (
	"fmt"
)

func main() {
	x := 10
	y := 20

	fmt.Printf("Before swapping, x: %d, y: %d\n", x, y)
	x, y = y, x
	fmt.Printf("After swapping, x: %d, y: %d\n", x, y)
}

Output:

Before swapping, x: 10, y: 20
After swapping, x: 20, y: 10

26) What are some useful built-in functions in Go language?

Some of the useful built-in functions in Go are,

Function Description
print(), println() These are used for printing the output.
len() It is used to get the length of the array, slice, map, string, Chan type data, etc.
cap() It is used to get the capacity of the array, slice, map, string, Chan type data, etc.
new() It is used for memory allocation. new (T) allocates zero value of type T and returns its pointer to type T.
make() It is used for memory allocation of a reference type (slice, map, Chan) and returns an initialized value, and the usage of different types is different.
copy() It is used to copy a slice.
append() It is used to append elements to a slice.
panic(), recover() These functions are used for error handling.
delete() It is used to delete the specified key in the map.

27) What is the default value of a slice in Go language?

A slice is a variable-length sequence that stores elements of a similar type. The default value of a slice variable in the Go programming language is nil. The length and capacity of a nil slice is 0. But if you print the nil slice – the output will be "[]".

Example:

// Golang program to demonstrate the
// default value of a slice

package main

import "fmt"

func main() {
	var x []int

	fmt.Println("Default value of a slice is", x)
	fmt.Println("Length of an empty slice is", len(x))
	fmt.Println("Capacity of an empty slice is", cap(x))
}

Output:

Default value of a slice is []
Length of an empty slice is 0
Capacity of an empty slice is 0

28) What is the default value of a map in Go language?

A map is a collection of unordered pairs of key-value. The default value of a map variable in the Go programming language is nil. The length of a nil map is o. But if you print the nil map – the output will be "map[]".

Example:

// Golang program to demonstrate the
// default value of a map

package main

import "fmt"

func main() {
	var x map[string]interface{}

	fmt.Println("Default value of a map is", x)
	fmt.Println("Length of an empty map is", len(x))
}

Output:

Default value of a map is map[]
Length of an empty map is 0

29) What is the default value of an empty interface in Go language?

An interface is a custom type that is used to specify a set of one or more method signatures. The default value of an empty interface in the Go programming language is nil.

Example:

// Golang program to demonstrate the
// default value of an empty interface

package main

import "fmt"

func main() {
	var x interface{}

	fmt.Println("Default value of an empty interface is", x)
}

Output:

Default value of an empty interface is <nil>

30) Which format verb with fmt.Printf() is used to print the type of a variable in Go?

In Go programming language, fmt.Printf() function is an inbuilt function of fmt package, it is used to format according to a format specifier and writes to standard output.

To print the type of a variable using the fmt.Printf() function – we use %T format verb.

Consider the below example,

// Golang program to demonstrate the
// example of %T format verb

package main

import "fmt"

func main() {
	// Declaring some variable with the values
	a := 10
	b := 123.45
	c := "Hello, world!"
	d := []int{10, 20, 30}

	// Printing types & values of the variables
	fmt.Printf("%T, %v\n", a, a)
	fmt.Printf("%T, %v\n", b, b)
	fmt.Printf("%T, %v\n", c, c)
	fmt.Printf("%T, %v\n", d, d)
}

Output:

int, 10
float64, 123.45
string, Hello, world!
[]int, [10 20 30]

31) Which format verb with fmt.Printf() is used to print the double-quoted text in Go?

In Go programming language, fmt.Printf() function is an inbuilt function of fmt package, it is used to format according to a format specifier and writes to standard output.

To print the type of a variable using the fmt.Printf() function – we use %T format verb.

Consider the below example,

// Golang program to demonstrate the
// example of %q format verb

package main

import "fmt"

func main() {
	// Declaring some variable with the values
	x := "Hello"
	y := "Hello, World!"

	// Printing double-quoted text
	fmt.Printf("%q\n", x)
	fmt.Printf("%q\n", y)
}

Output:

"Hello"
"Hello, World!"

32) Does Go support implicit conversion?

Just like C and C++ programming language, the Go programming language does not support implicit type conversion (or, automatic type conversion) even if the datatypes are compatible.


33) What form of type conversion does Go support?

Go programming language supports explicit type conversion. It does not support implicit type conversion due to its strong type system.

Consider the syntax,

new_type (variable/value)

Consider the example,

// Golang program to demonstrate the
// example of explicit type conversion

package main

import "fmt"

func main() {
	var VarInt int
	var VarFloat float32

	VarFloat = 123.45
	// Converting float32 to int
	VarInt = int(VarFloat)

	// Printing the values
	fmt.Println(VarInt)
	fmt.Println(VarFloat)
}

Output:

123
123.45

34) Does Go language have ternary operator?

No. Go programming language does not have a ternary operator. You may use the following to achieve the same result:

if expr {
    // true block
} else {
    // false block
}

35) Explain what are string literals?

A string literal represents a string constant containing a sequence of characters. There are two types of strings literals,

  • Raw string literals:
    The raw string literals are character sequences enclosed within the backquotes (``).
  • Interpreted string literals:
    The interpreted string literals are character sequences enclosed within the double quotes ("").

Consider the below example – demonstrating the examples of raw and interpreted string literals,

// Go program to demonstrate the
// examples Raw and Interpreted
// string literal

package main

import (
	"fmt"
)

func main() {
	// Raw string literal
	x := `Hello\tworld\nHow're you?`

	// Interpreted string literal
	y := "Hello\tworld\nHow're you?"

	fmt.Println("x :", x)
	fmt.Println("y :", y)
}

Output:

x : Hello\tworld\nHow're you?
y : Hello	world
How're you?

In the above program, variable x contains the raw string literal and variable y contains the interpreted raw string.


36) Does Go language have exceptions?

No, the Go language does not have the concept of expectations handling, it has a different approach. For the plain error handling – we can use the multi-value returns approach to report and return an exception. Go code uses error values to indicate an abnormal state.

Consider the below example – Here we are trying to open a file that does not exist,

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.ReadFile("myfile.txt")
	// If there is an error
	if err != nil {
		fmt.Println("File does not exist\nThe Error is:", err)
		os.Exit(0)
	}

	// If file exists then  print the content
	fmt.Println("The file's content is:")
	os.Stdout.Write(f)
}

Output:

File does not exist
The Error is: open myfile.txt: no such file or directory

37) Does Go language supports recursion?

Yes, Go supports recursive functions (recursion). Recursion is the process in which a function calls itself.

Consider the below example,

package main

import (
	"fmt"
)

// Recursion function
func fact(n int) int {
	if n == 0 {
		return 1
	}
	return n * fact(n-1)
}

func main() {
	x := 5
	factorial := fact(x)
	fmt.Println("Factorial of", x, "is", factorial)

	x = 15
	factorial = fact(x)
	fmt.Println("Factorial of", x, "is", factorial)
}

Output:

Factorial of 5 is 120
Factorial of 15 is 1307674368000

38) What is a closure in Golang?

Go programming language supports a special feature known as an anonymous function. An anonymous function can form a closure.

The closure is a special type of anonymous function that references variables declared outside of the function itself. This concept is similar to access the global variables which are available before the declaration of the function.

Consider the below example,

package main

import "fmt"

// Closure function
func counter() func() int {
	x := 0
	return func() int {
		x++
		return x
	}
}

func main() {
	cntfunc := counter()
	fmt.Println("[1] cntfunc():", cntfunc())
	fmt.Println("[2] cntfunc():", cntfunc())
	fmt.Println("[3] cntfunc():", cntfunc())
	fmt.Println("[4] cntfunc():", cntfunc())

	cntfunc = counter()
	fmt.Println("[5] cntfunc():", cntfunc())
}

Output:

[1] cntfunc(): 1
[2] cntfunc(): 2
[3] cntfunc(): 3
[4] cntfunc(): 4
[5] cntfunc(): 1

39) Can closure be a recursive in Golang?

Yes, a closure can also be recursive, but this requires the closure to be declared with a typed var explicitly before it's defined.

Consider the below example,

package main

import "fmt"

func main() {
	// Recursive closure function
	var InfinitePrinting func()
	InfinitePrinting = func() {
		fmt.Println("Hello")
		InfinitePrinting()
	}

	// The function calling
	InfinitePrinting()
}

Output:

Hello
Hello
Hello
Hello
Hello
.
.
.
Infinite times

40) Can you return multiple values from a function?

Yes, a Golang function can return multiple values.

Consider the below example,

package main

import (
	"fmt"
)

func FindSumAndSub(x, y int) (int, int) {
	return (x + y), (x - y)
}

func main() {
	sum, sub := FindSumAndSub(10, 20)
	fmt.Println(sum, ",", sub)

	sum, sub = FindSumAndSub(50, 10)
	fmt.Println(sum, ",", sub)
}

Output:

30 , -10
60 , 40

41) Does the Go language have function/method overloading?

Go language does not support function/method overloading.

As per the Go FAQs, below is the explanation why does Go not support the overloading of methods and operators?

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.


42) Does Go have a runtime?

Go programming language has a library called "runtime", which is a part of every Go program, it is used for implementing garbage collection, concurrency, stack management, and other critical features.


43) Explain Go for range?

The Go for range form can be used to iterate over strings, arrays, slices, maps, and channels.

Consider the below example,

package main

import "fmt"

func main() {

	x := []int{10, 20, 30, 35, 60}

	for index, element := range x {
		fmt.Printf("[%d] %d\n", index, element)
	}
}

Output:

[0] 10
[1] 20
[2] 30
[3] 35
[4] 60

44) What is a pointer in Go language?

In Go programming language, a pointer is a special type of variable that is used to store the memory address of another variable.

Consider the below example,

// Go program to demonstrate the
// example of pointers

package main

import (
	"fmt"
)

func main() {
	var x int   // int variable
	var px *int // int pointer

	x = 10
	// Pointer assignment
	px = &x

	// Printing the value using x
	fmt.Println("x =", x)
	// Printing the value using px
	fmt.Println("px =", *px)
}

Output:

x = 10
px = 10

In the above program, x is an integer variable and px is an integer pointer. The statement px=&x is assigning the address of x to the pointer variable px. To access the value using the pointer variable, we use the asterisk sign (*). This *px is using to get the value of x.


45) Does the standard Go compiler support function inlining in Go?

Yes, the standard Go compiler supports inlining functions. The compiler will automatically inline some very short functions which satisfy certain requirements. The specific inline requirements may change from version to version.

Please note, there are no explicit ways to define a function as an inline function in the program.


46) How to get current date and time in Go language?

In Go programming language, to get the current date and time, we need to import the time package. The Now() function of the time package is used to get the current date and time.

Consider the below program,

package main

import (
	"fmt"
	"time"
)

func main() {
	dt := time.Now()
	fmt.Println("Current date and time is: ", dt.String())
}

Output:

Current date and time is:  2009-11-10 23:00:00 +0000 UTC m=+0.000000001

47) What is the difference between concurrent and parallelism in Golang?

In Go programming language, concurrency is when a program can handle multiple tasks at once, while parallelism is when your program can execute multiple tasks at once using multiple processors.

The concurrency is a property of a program while parallelism is a runtime property. The concurrency allows handle multiple tasks at the same time but it is not necessary executing them. While parallelism allows executing multiple tasks at the same time.


48) What is the easiest way to check if a slice is empty?

The easiest way to check if a slice is empty – to check the length of the slice, if it's 0 then the slice is an empty slice. To get the length of a slice, we use the len() function which is an inbuilt function.

Consider the below example,

package main

import (
	"fmt"
)

func main() {
	s1 := []int{}
	s2 := []int{10, 20, 30, 40, 50}

	fmt.Println("s1:", s1)
	fmt.Println("s2:", s2)

	if len(s1) == 0 {
		fmt.Println("s1 is empty!")

	} else {
		fmt.Println("s1 is not empty!")
	}

	if len(s2) == 0 {
		fmt.Println("s2 is empty!")

	} else {
		fmt.Println("s2 is not empty!")
	}
}

Output:

s1: []
s2: [10 20 30 40 50]
s1 is empty!
s2 is not empty!

49) Why are there no untagged unions in Go, as in C?

Untagged unions are not allowed in the Go language because it would violate Go's memory safety guarantees.


50) What's the difference between new() and make() functions in Go?

The new() functions is used to allocate memory, while the make() function initializes the slice, map, and channel types.

Read more: new() and make() functions in Go.

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.