Add Method to Struct Type
You can also add methods to struct types using a method receiver. A method EmpInfo is added to the Employee struct.
Example
package main
import "fmt"
type Salary struct {
Basic, HRA, TA float64
}
type Employee struct {
FirstName, LastName, Email string
Age int
MonthlySalary []Salary
}
func (e Employee) EmpInfo() string {
fmt.Println(e.FirstName, e.LastName)
fmt.Println(e.Age)
fmt.Println(e.Email)
for _, info := range e.MonthlySalary {
fmt.Println("===================")
fmt.Println(info.Basic)
fmt.Println(info.HRA)
fmt.Println(info.TA)
}
return "----------------------"
}
func main() {
e := Employee{
FirstName: "Mark",
LastName: "Jones",
Email: "mark@gmail.com",
Age: 25,
MonthlySalary: []Salary{
Salary{
Basic: 15000.00,
HRA: 5000.00,
TA: 2000.00,
},
Salary{
Basic: 16000.00,
HRA: 5000.00,
TA: 2100.00,
},
Salary{
Basic: 17000.00,
HRA: 5000.00,
TA: 2200.00,
},
},
}
fmt.Println(e.EmpInfo())
}
Most Helpful This Week
Example: How to use ReadFull from IO Package in Golang?
Golang Concurrency Best Practices
Invalid memory address or nil pointer dereference error in Golang
Illustration of Sleeping Barber Problem in Golang
Golang program for implementation of Selection Sort
How do you handle HTTP responses in Go?
Find odd and even numbers using goroutines and channels
Golang program for implementation of Bubble Sort
React JS Count number of checkboxes are checked
How to copy one slice items into another slice in Golang?