Interfaces
are collection of method signatures.
‘interface’
keyword is used to create interfaces.
Example
type Details
interface {
aboutMe()
id() int
}
How can a type implement an interface?
You just
need to implement all the methods in the interface (You even no need to
explicitly specify that you are implementing an interface, you just write the
implementation, this is called duck typing.).
For
example, Employee type implements Details interface.
type
Employee struct {
name string
id
int
}
func (emp
*Employee) aboutMe() {
fmt.Println("name : ",
emp.name, ", id : ", emp.id)
}
func (emp
*Employee) getId() int {
return emp.id
}
If you
define ‘printMyDetails’ method by adding Details object as an argument, you can
pass any object of type ‘T’ that implements Details interface.
func
printMyDetails(obj Details) {
obj.aboutMe()
}
In Go, if
your type implements all the methods of the interface, then your type can be
stored in a value of interface type. For example, Details object can store
Employee object.
emp1 := &Employee{"Krishna",
123}
printMyDetails(emp1)
App.go
package main import ( "fmt" ) type Details interface { aboutMe() getId() int } type Employee struct { name string id int } func (emp *Employee) aboutMe() { fmt.Println("name : ", emp.name, ", id : ", emp.id) } func (emp *Employee) getId() int { return emp.id } func printMyDetails(obj Details) { obj.aboutMe() } func main() { emp1 := &Employee{"Krishna", 123} printMyDetails(emp1) }
Output
name : Krishna , id : 123
No comments:
Post a Comment