Go语言基础总结
package main
import (
"fmt"
)
// 定义一个结构体来表示一个员工
type Employee struct {
ID int
FirstName string
LastName string
Salary int
}
// 定义一个接口来表示可以进行员工管理的系统
type EmployeeManager interface {
AddEmployee(employee Employee)
RemoveEmployee(id int)
UpdateEmployeeSalary(id int, newSalary int)
GetEmployee(id int) Employee
ListEmployees() []Employee
}
// 实现EmployeeManager接口的具体结构体
type BasicManager struct {
employees map[int]Employee
}
// 实现AddEmployee方法
func (manager *BasicManager) AddEmployee(employee Employee) {
manager.employees[employee.ID] = employee
}
// 实现RemoveEmployee方法
func (manager *BasicManager) RemoveEmployee(id int) {
delete(manager.employees, id)
}
// 实现UpdateEmployeeSalary方法
func (manager *BasicManager) UpdateEmployeeSalary(id int, newSalary int) {
if employee, exists := manager.employees[id]; exists {
employee.Salary = newSalary
manager.employees[id] = employee
}
}
// 实现GetEmployee方法
func (manager *BasicManager) GetEmployee(id int) Employee {
return manager.employees[id]
}
// 实现ListEmployees方法
func (manager *BasicManager) ListEmployees() []Employee {
employees := make([]Employee, len(manager.employees))
i := 0
for _, employee := range manager.employees {
employees[i] = employee
i++
}
return employees
}
func main() {
// 创建一个BasicManager实例
manager := &BasicManager{
employees: make(map[int]Employee),
}
// 添加员工
manager.AddEmployee(Employee{ID: 1, FirstName: "John", LastName: "Doe", Salary: 50000})
// 获取员工信息
employee := manager.GetEmployee(1)
fmt.Printf("Employee ID %d: %v\n", employee.ID, employee)
// 更新员工薪水
manager.UpdateEmployeeSalary(1, 55000)
updatedEmployee := manager.GetEmployee(1)
fmt.Printf("Updated Employee ID %d: %v\n", updatedEmployee.ID, updatedEmployee)
// 列出所有员工
employees := manager.ListEmployees()
fmt.Println("All Employees:")
for _, employee := range employees {
fmt.Printf("%v\n", employee)
}
}
这段代码定义了一个Employee
结构体来表示员工,并定义了一个EmployeeManager
接口来描述可以进行员工管理的系统所需的方法。然后,我们实现了BasicManager
结构体来满足这个接口的要求,并在main
函数中演示了如何使用它来添加、获取、更新和列出员工信息。这个示例展示了接口的使用,以及如何通过结构体实现这些接口。
评论已关闭