Quantcast
Viewing all articles
Browse latest Browse all 30

Embedded fields in structs

main.go
package main
import (
"fmt"
)
typeFruitstruct {
Namestring
Colorstring
}
// You can define functions on either the "base" ...
func (f*Fruit) Announce() {
fmt.Printf("I am %s, and I am %s\n", f.Color, f.Name)
}
// Here adding "Fruit" is called embedding fields, and I've also seen "promoted fields" because they come from Fruit
typeAvocadostruct {
Fruit
IsRipebool
}
// And we can define functions on the struct with embedded fields
// We cannot reference fields / methods for one of these classes on a parent.
// E.g., Fruit could not have a function that uses IsRipe (although it would be appropriate huh?)
func (a*Avocado) IsReady() {
ifa.IsRipe {
fmt.Printf("I am %s, and I am %s, and I am ripe!\n", a.Color, a.Name)
} else {
fmt.Printf("I am %s, and I am %s, and I am NOT ripe!\n", a.Color, a.Name)
}
}
funcmain() {
// This does not work!
// avocado := Avocado{Name: "Harry the avocado", Color: "green", IsRipe: true}
// ./main.go:19:21: cannot use promoted field Fruit.Name in struct literal of type Avocado
// ./main.go:19:48: cannot use promoted field Fruit.Color in struct literal of type Avocado
// Instead, pass the "base" type to the underlying type
avocado:=Avocado{Fruit: Fruit{Name: "Harry the avocado", Color: "green"}, IsRipe: true}
// This function is on the base struct
avocado.Announce()
// I am green, and I am Harry the avocado
// This function
avocado.IsReady()
// I am green, and I am Harry the avocado, and I am ripe!
// There is a proposal to make this easier!
// https://github.com/golang/go/issues/9859
}
main.py
#!/usr/bin/env python3
classFruit:
def__init__(self, name, color):
self.name=name
self.color=color
defAnnounce(self):
print(f"I am {self.color}, and I am {self.name}")
classAvocado(Fruit):
def__init__(self, name, color, is_ripe):
super().__init__(name, color)
self.is_ripe=is_ripe
defIsReady(self):
ifself.is_ripe:
print(f"I am {self.color}, and I am {self.name}, and I am ripe!")
else:
print(f"I am {self.color}, and I am {self.name}, and I am NOT ripe!")
defmain():
avocado=Avocado(name="Harry the avocado", color="green", is_ripe=True)
avocado.Announce()
# I am green, and I am Harry the avocado
avocado.IsReady()
# I am green, and I am Harry the avocado, and I am ripe!
if__name__=="__main__":
main()

Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>