Skip to content

Instantly share code, notes, and snippets.

@vsoch
Last active October 13, 2021 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsoch/dd34ac96dc463c0a2f18c53aea67cf37 to your computer and use it in GitHub Desktop.
Save vsoch/dd34ac96dc463c0a2f18c53aea67cf37 to your computer and use it in GitHub Desktop.
Embedded fields in structs
package main
import (
"fmt"
)
type Fruit struct {
Name string
Color string
}
// 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
type Avocado struct {
Fruit
IsRipe bool
}
// 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() {
if a.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)
}
}
func main() {
// 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
}
#!/usr/bin/env python3
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def Announce(self):
print(f"I am {self.color}, and I am {self.name}")
class Avocado(Fruit):
def __init__(self, name, color, is_ripe):
super().__init__(name, color)
self.is_ripe = is_ripe
def IsReady(self):
if self.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!")
def main():
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment