闽公网安备 35020302035485号
package user
import "fmt"
type User struct {
ID int
Name string
}
func CreateUser(id int, name string) User {
return User{ID: id, Name: name}
}
func PrintUser(u User) {
fmt.Printf("User ID: %d, Name: %s\n", u.ID, u.Name)
}
2. 封装:package main
import (
"fmt"
)
type Employee struct {
ID int
Name string
Salary float64
isManager bool
}
func NewEmployee(id int, name string, salary float64, isManager bool) Employee {
return Employee{
ID: id,
Name: name,
Salary: salary,
isManager: isManager,
}
}
func (e *Employee) SetManagerStatus(isManager bool) {
e.isManager = isManager
}
func (e Employee) PrintDetails() {
fmt.Printf("ID: %d\nName: %s\nSalary: %.2f\nManager: %v\n", e.ID, e.Name, e.Salary, e.isManager)
}
func main() {
emp := NewEmployee(1, "Alice", 50000.0, false)
emp.PrintDetails()
// Try to change manager status directly (encapsulation prevents this)
// emp.isManager = true // Uncommenting this will result in a compilation error
emp.SetManagerStatus(true)
emp.PrintDetails()
}
在这个示例中:Go模块是Go包的集合,每个项目都是一个模块。模块中使用的包由Go通过go.mod文件进行管理。Go模块使用语义化版本(Semver)系统进行版本控制,版本号由三部分组成:主版本、次版本和修订版本。例如,版本号为1.2.3的包中,1是主版本,2是次版本,3是修订版本。