How to convert an object from an interface to concrete type in Go
Overview
When we have to convert an interface{} type object to a concrete type, we can use the .(type) operator.
What is an interface{}?
An interface{} is a collection of type implementable method signature.
Syntax
type interface_name interface{
//Method signature
}
Parameters
interface{} accepts method signatures.
Why we use interface{}
One of the basic reasons to use an interface is that it makes interactions with third-party packages easier.
What is the .(type) operator?
.(type) is an operator used to group expressions.
Parameters
The type operator accepts expressions as arguments.
How to convert an interface to a concrete type
Below is an example of how to convert an object from an interface to a concrete type.
package mainimport "fmt"type Person struct {firstName stringlastName string}func main() {person := Person{firstName: "Joe",lastName: "Bloggs",}printIfPerson(person)}func printIfPerson(object interface{}) {person, ok := object.(Person)if ok {fmt.Printf("Hello %s!\n", person.firstName)}}
Explanation
In line 5, we make an interface type object, Person.
In lines 11-14, we add “Joe Bloggs” as a Person to the interface object.
In line 19, we create a function for the conversion of the object from an interface type to a concrete type.
In line 20, we access the values of the interface{} object type.
In line 23, we print our output.