How to Cast Interface Into Concrete Type in Go
The interfaces of the Go language are distinct from those of other languages. The interface is a type in the Go language used to express a collection of one or more method signatures.
It is abstract; thus, you cannot construct an instance of it. However, you are permitted to establish an interface type variable, which can be assigned a concrete type value containing the interface’s required methods.
Or, to put it another way, the interface is both a set of methods and a custom type.
This tutorial will demonstrate how to cast interface into concrete type in Go.
Cast Interface Into Concrete Type in Go
The .(type)
operator is useful for converting an interface-type object into a concrete type. A collection of type implementable method signatures makes up an interface.
In this example, we create a Person
interface type object. We add Jay Singh
as a Person
to the interface object, write a method to convert the object from an interface type into a concrete type, access the interface object type’s data, and display our result.
package main
import "fmt"
type Person struct {
firstName string
lastName string
}
func main() {
person := Person{
firstName: "Jay",
lastName: "Singh",
}
printIfPerson(person)
}
func printIfPerson(object interface{}) {
person, ok := object.(Person)
if ok {
fmt.Printf("Hello %s!\n", person.firstName)
}
}
Output:
Hello Jay!