为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题
在本节中,我们将重点关注结构体方法。在此之前,您需要了解什么是结构体。Golang 中的结构体是用户定义类型,包含命名字段/属性的集合。这意味着它将可能不同类型的项组合成一个单一类型或单一单元。通过使用 struct 关键字,您可以在 Go 中定义一个结构体。
示例
type Employee struct {
id int
name string
post string
salary int
}
这里使用 type 关键字来引入一个新类型。它后面跟着类型名 Employee。struct 关键字用于指示我们正在定义一个结构体类型,并在花括号内列出结构体的字段,如 id、name、post 和 salary。这里每个字段都有一个名称和一个类型。
在 Go 编程中,结构体也可以通过使用结构体对象来定义方法。当方法附加到结构体时,它像普通函数一样工作。但它还需要额外指定其类型。
type type_name struct { }
func (m type_name) function_name() int {
//code
}
在本节中,我们将重点关注结构体。例如,员工记录包含 id、姓名、职位、一日工资和休假。将这五个属性分组到一个单一的结构体 **Employee** 中是很有意义的。通过使用结构体概念,您可以读取和显示员工记录。
下面给出的程序将解释如何在 Go 编程中创建结构体,创建实例,为结构体实例设置值,以及读取和打印结构体实例。
这里我们可以使用内置函数 fmt.scanln() 来读取输入值。输出可以使用内置函数 fmt.println() 来显示。这两个内置函数都在 fmt 包中定义。为了使用这些函数,我们应该将“**fmt**”包导入到我们的程序中。
下面是 Go 程序中用于实现结构体方法的步骤。
步骤 1:开始
步骤 2:导入包 **fmt**
步骤 3:定义一个结构体 'Employee',包括员工的 id、姓名、职位、一日工资和休假。
步骤 4:打开 **main()** 开始程序,GO 程序执行从 **main()** 开始
步骤 5:声明结构体变量 **emp1**
步骤 6:使用 **emp1** 读取员工详细信息
步骤 7:使用结构体方法 show() 显示员工详细信息。
步骤 8:通过调用结构体方法 totalWorkingDays() 将员工工作天数计算到 **w** 中
步骤 9:显示员工工作天数
步骤 10:通过调用结构体方法 calculateSalary(w) 计算并显示员工月工资
步骤 11:退出
步骤 1:借助结构体对象 **e** 显示学生详细信息
步骤 1:返回 30 - e.leave 的值
步骤 1:返回 workingDays X e.daySalary 的值
package main
import (
"fmt"
)
//define a struct 'Employee'
type Employee struct {
id int
name string
post string
daySalary int
leave int
}
func (e Employee) show() {
// displays student details
fmt.Println("Employee Details")
fmt.Println("----------------")
fmt.Printf("Id: %d\n", e.id)
fmt.Printf("Name: %s\n", e.name)
fmt.Printf("post: %s\n", e.post)
fmt.Printf("Salary of one day: %d\n", e.daySalary)
fmt.Printf("leave: %d\n", e.leave)
}
// Methods to calculate total working days using struct instance
func (e Employee) totalWorkingDays() int {
return (30-e.leave)
}
// Struct Methods to calculate total Salary of month
func (e Employee)calculateSalary(workingDays int) int {
return (workingDays * e.daySalary)
}
func main() {
var emp1 Employee
// setting values
emp1.id = 101
emp1.name ="Employee 1"
emp1.post ="Admin"
emp1.daySalary=500
emp1.leave=5
// displays Employee details
emp1.show()
// displays Employee Working Days
var w int
w = emp1.totalWorkingDays()
fmt.Printf("Total Working Days: %d\n", w)
// displays Employee Salary
fmt.Printf("Total Salary of month: %d\n", emp1. calculateSalary(w))
}
Employee Details ---------------- Id: 101 Name: Employee 1 post: Admin Salary of one day: 500 leave: 5 Total Working Days: 25 Total Salary of month: 12500