Defining a type that satisfies an interface in Go Programming Language
Defines an interface type named Employee with two methods. Then it defines a type named Emp that satisfies Employee.
We define all the methods on Emp that it needs to satisfy Employee
If a type has all the methods declared in an interface, then no further declarations needed explicitly to say that Emp satisfies Employee.
Declares an e1 variable with Employee as its type, then creates a Emp value and assigns it to e1.
Example
package main
import "fmt"
// Employee is an interface for printing employee details
type Employee interface {
PrintName(name string)
PrintSalary(basic int, tax int) int
}
// Emp user-defined type
type Emp int
// PrintName method to print employee name
func (e Emp) PrintName(name string) {
fmt.Println("Employee Id:\t", e)
fmt.Println("Employee Name:\t", name)
}
// PrintSalary method to calculate employee salary
func (e Emp) PrintSalary(basic int, tax int) int {
var salary = (basic * tax) / 100
return basic - salary
}
func main() {
var e1 Employee
e1 = Emp(1)
e1.PrintName("John Doe")
fmt.Println("Employee Salary:", e1.PrintSalary(25000, 5))
}
Most Helpful This Week
Interfaces with similar methods in Go Programming Language
How to declare Interface Type in Go Programming Language
Polymorphism in Go Programming Language
Empty Interface Type in Go Programming Language
Implementing Multiple Interfaces in Go Programming Language
Interface Accepting Address of the Variable in Golang
Interface embedding another interface in Go Programming Language