Hello John,
thanks for the time to look through the code.. I attached what I
did.. I am trying to use the pointer way of embedding as,
type CardboardBox struct {
// An anonymous field, all fields of RectPrism are promoted
into CardboardBox
*RectPrism
isSoggy bool
}
It compiles, but gets a run time error
panic: runtime error: invalid memory address or nil pointer
dereference
[signal 0xb code=0x1 addr=0x0 pc=0x8048e26]
runtime.panic+0x9f /root/repo/go/src/pkg/runtime/proc.c:1023
thanks all for the reply.. i still has to go through it throughly..
will respond after..
-------------------- START ----------------------
package main
import (
"fmt"
)
// Declare an Interface to a 3d Solid
type Solid interface {
Volume() float32
SurfaceArea() float32
}
// Contains the Fields for defining a Rectangular Prism's Dimension's
type RectPrism struct {
L, w, h float32
}
// RectPrism implements the Solid Interface
func (r *RectPrism) Volume() float32 {
return (r.L * r.w * r.h)
}
func (r *RectPrism) SurfaceArea() float32 {
return (2*(r.L*r.w) + 2*(r.L*r.h) + 2*(r.w*r.h))
}
// This Class is going to inherit from RectPrism
type CardboardBox struct {
// An anonymous field, all fields of RectPrism are promoted
into CardboardBox
*RectPrism
isSoggy bool
}
// This CardboardBox has the top Open so we must reimplement the
SurfaceArea func
// Inherits CardboardBox
type OpenCardboardBox struct {
CardboardBox
}
// Reimplement the SurfaceArea Function for OpenCardboardBox since it
doesn't have a top
func (this *OpenCardboardBox) SurfaceArea() float32 {
return (this.CardboardBox.SurfaceArea() + 2*(this.L*this.h) +
2*(this.w*this.h))
}
func main() {
fmt.Printf("\n\n")
cbox := &CardboardBox{&RectPrism{2,4,2},true}
/*cbox.L = 2
cbox.w = 4
cbox.h = 2
cbox.isSoggy = true*/
obox := new(OpenCardboardBox)
obox.L = 2
obox.w = 4
obox.h = 2
obox.isSoggy = true
// CardboardBox implements the RectPrism interface
// through the anonymous field RectPrismStruct
// This Aggregates the RectPrismStruct into CardboardBox
var rprism Solid = cbox
fmt.Printf(" Volume: %f\n", rprism.Volume())
fmt.Printf("Surface Area: %f\n", rprism.SurfaceArea())
rprism = obox
fmt.Printf(" Volume: %f\n", rprism.Volume())
fmt.Printf("Surface Area: %f\n", rprism.SurfaceArea())
fmt.Printf("\n\n")