Inheritance

There is no inheritance in Go, but you can embed types. Here is an example of a Person and Doctor types, which embeds the Person type. Instead of inheriting the behavior of Person directly, it stores the Person object as a variable, which brings with it all of its expected Person methods and attributes:

package mainimport (   "fmt"   "reflect")type Person struct {   Name string   Age  int} 
type Doctor struct {   Person         Person   Specialization string}func main() {   nanodano := Person{      Name: "NanoDano",      Age:  99,   } 
   drDano := Doctor{      Person:         nanodano,      Specialization: "Hacking",   }   fmt.Println(reflect.TypeOf(nanodano))   fmt.Println(nanodano)
   fmt.Println(reflect.TypeOf(drDano))   fmt.Println(drDano)} 

Get Security with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.