When we have to convert an interface{}
type object to a concrete type, we can use the .(type)
operator.
interface{}
?An interface{}
is a collection of type implementable method signature.
type interface_name interface{
//Method signature
}
interface{}
accepts method signatures.
interface{}
One of the basic reasons to use an interface is that it makes interactions with third-party packages easier.
.(type)
operator?.(type)
is an operator used to group expressions.
The type operator accepts expressions as arguments.
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)}}
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.