Inheritance in Object Oriented Programming in Golang

Create new folder named entities. In entities folder, create new entities as below:

In entities folder, create new file named human.go as below:

package entities

import "fmt"

type Human struct {
	Name   string
	Gender string
}

func NewHuman(name string, gender string) Human {
	human := Human{name, gender}
	return human
}

func (human Human) ToString() string {
	return fmt.Sprintf("name: %s\ngender: %s", human.Name, human.Gender)
}

In entities folder, create new file named student.go as below:

package entities

import "fmt"

type Student struct {
	Id    string
	Score float64
	Human Human
}

func NewStudent(id string, score float64, human Human) Student {
	student := Student{id, score, human}
	return student
}

func (student Student) ToString() string {
	return fmt.Sprintf("id: %s\nscore: %0.2f\n%s", student.Id, student.Score, student.Human.ToString())
}




In entities folder, create new file named employee.go as below:

package entities

import "fmt"

type Employee struct {
	Id     string
	Salary float64
	Human  Human
}

func NewEmployee(id string, salary float64, human Human) Employee {
	employee := Employee{id, salary, human}
	return employee
}

func (employee Employee) ToString() string {
	return fmt.Sprintf("id: %s\nsalary: %0.2f\n%s", employee.Id, employee.Salary, employee.Human.ToString())
}

Create new folder named src. In src folder, create new file named main.go as below:

package main

import (
	"entities"
	"fmt"
)

func main() {

	student := entities.Student{
		Id:    "st01",
		Score: 7.8,
		Human: entities.Human{
			Name:   "Name 1",
			Gender: "male",
		},
	}
	fmt.Println("Student Info")
	fmt.Println(student.ToString())

	employee := entities.Employee{
		Id:     "e01",
		Salary: 1000,
		Human: entities.Human{
			Name:   "Name 2",
			Gender: "female",
		},
	}
	fmt.Println("Employee Info")
	fmt.Println(employee.ToString())

}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

Student Info
id: st01
score: 7.80
name: Name 1
gender: male

Employee Info
id: e01
salary: 1000.00
name: Name 2
gender: female