26 Structs Instead of Classes - OOP in Go

31 阅读1分钟

Structs Instead of Classes

Create a subfolder inside ~/Documents/ and name it oop.

go mod init oop
├── Documents
│   └── oop
│       ├── employee
│       │   └── employee.go
│       └── go.mod

Please replace the contents of employee.go with the following,

package employee

import (  
    "fmt"
)

type employee struct {  
    firstName   string   //私有化
    lastName    string
    totalLeaves int
    leavesTaken int
}

func New(firstName string, lastName string, totalLeave int, leavesTaken int) employee {
	e := employee {firstName, lastName, totalLeave, leavesTaken}
	return e
}

func (e employee) LeavesRemaining() {  
    fmt.Printf("%s %s has %d leaves remaining\n", e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))
}


package main  

import "oop/employee"

func main() {  
    e := employee.New("Sam", "Adolf", 30, 20)
    e.LeavesRemaining()
}