Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Reflection in Golang
3.
Copy() method
4.
DeepEqual() method
5.
Swapper() method
6.
TypeOf() method
7.
ValueOf() method
8.
Need for Reflection in Golang
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

Go Reflect

Author APURV RATHORE
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Golang is syntactically comparable to C, and it is clear, clean, and efficient, much like C. The foundations of golang are simple to learn if you are familiar with C ideas. We shall cover the reflection in golang, which is one of the fundamentals of Golang, in this post.

The programming language Golang is simple to learn. Anyone who is familiar with the principles of programming may learn the basics in a few hours. The complete language specification is only a few pages long due to its simplicity.

Reflection is an integral fundamental component of golang, so it is very important for one to understand reflection to get fully acquainted with the golang. 

In this blog, we will discuss more about Reflection in Golang. 

Reflection in Golang

Reflection is a type of metaprogramming in Go. Reflection enables us to inspect types in real-time. It also allows you to examine, alter, and create variables, functions, and structs while they're running. The reflect package in Go allows you to view and change an object while it is running. Reflection is a valuable tool for programmers that broadens the scope of any programming language. Types, Kinds, and Values are three fundamental reflection elements that are utilised to gather information.

We will understand reflection by going over its main methods.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Copy() method

Until either the destination or the source has been exhausted, copy copies the contents of the source into the destination. The number of items copied is returned. Both the destination and the source must have the same element type and have the same kind of Slice or Array.

 

Example:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    varOne := reflect.ValueOf([]string{"s", "q", "j"})
    varTwo := reflect.ValueOf([]string{"h", "u", "j"})

    cnt := reflect.Copy(varOne, varTwo)
    fmt.Println("Value of cnt:")
    fmt.Println(cnt)
    fmt.Println("varTwo:")
    fmt.Println(varTwo)
    fmt.Println("varOne:")
    fmt.Println(varOne)
}

 

Output:

Value of cnt:
3
varTwo:
[h u j]
varOne:
[h u j]

DeepEqual() method

If both the input provided to the function are deeply equal, then the function returns True, else it returns False. Two arrays are said to be deeply equal when all the elements at their corresponding index are the same. If the relevant fields, both exported and un-exported, are deeply equal, the structure values are deeply identical.

 

Example:

package main

import (
"fmt"
"reflect"
)
type pen struct {
color   string
company string
}
func main() {
stringOne := []string{"q", "w"}
stringTwo := []string{"e", "r"}
isDeepEqual := reflect.DeepEqual(stringOne, stringTwo)
fmt.Println("The Result")
fmt.Println(isDeepEqual)

pen1 := pen{"red", "cello"}
pen2 := pen{"black", "cello"}
isDeepEqual = reflect.DeepEqual(pen1, pen2)
fmt.Println("The Result")
fmt.Println(isDeepEqual)
}

 

Output:

The Result
false
The Result
false

Swapper() method

The Swapper function swaps the elements in the given slice. You may also use this method to reverse or order the slice in a clever way.

 

Example:

package main

import (
"fmt"
"reflect"
)

func main() {
listOfInt := []int{1, 2, 3}
swap := reflect.Swapper(listOfInt)
fmt.Println("Original array")
fmt.Println(listOfInt)
swap(0, 2)
fmt.Println("Final array")
fmt.Println(listOfInt)
}

 

Output:

Original array
[1 2 3]
Final array
[3 2 1]

TypeOf() method

This function returns the type of the input passed, which is of the type reflect.Type. 

 

Example:

package main

import (
"fmt"
"reflect"
)

func main() {
listOfInt := []int{21, 29, 13, 74, 15}
fmt.Println("The type is ", reflect.TypeOf(listOfInt))

varInt := 9090
fmt.Println("The type is ", reflect.TypeOf(varInt))

varString := "This is a string"
fmt.Println("The type is ", reflect.TypeOf(varString))

}

 

Output:

The type is  []int
The type is  int
The type is  string

ValueOf() method

To generate a reflect.Value instance that represents the value of a variable uses the reflect.ValueOf() function.

 

Example:

package main

import (
"fmt"
"reflect"
)

func main() {
listOfInt := []int{22, 33, 44}
fmt.Println("The value is", reflect.ValueOf(listOfInt))

varString := "Hello World"
fmt.Println("The value is", reflect.ValueOf(varString))

varInt := 1000
fmt.Println("The value is", reflect.ValueOf(varInt))
fmt.Println("The value is", reflect.ValueOf(&varInt))
}

 

Output:

The value is [22 33 44]
The value is Hello World
The value is 1000
The value is 0xc000018058

Need for Reflection in Golang

The data given to the empty interfaces are often not primitives. They might also be structs, for example. We need to run procedures on such data without knowing what type it is or what values it contains. In this case, we need to know the types contained in the struct as well as the number of fields in order to execute various operations on it, such as interpreting the data included in it to query a database or design a schema for a database. Reflection may be used to solve these issues in real-time.

Check out this article - String slicing in Python

FAQs

  1. What are reflections in golang? 
    Reflection is a type of metaprogramming in Go. Reflection enables us to inspect types in real-time. It also allows you to examine, alter, and create variables, functions, and structs while they're running. The reflect package in Go allows you to view and change an object while it is running.
     
  2. How do reflections work in golang?
    In Golang, every type, including user-defined types, contains information about the type name, fields name, and function name. Golang's reflection just reads these values through some mechanism.

Key Takeaways

In this article, we have extensively discussed reflections in golang and their implementation in the Gol programming language. We hope that this blog has helped you enhance your knowledge regarding reflections and if you would like to learn more, check out our articles on GoLang. Do upvote our blog to help other ninjas grow. 

Happy Coding!

 

Live masterclass