Object serialization: Difference between revisions
Content added Content deleted
(→{{header|Go}}: updates for two library changes) |
(→{{header|Go}}: task conformance: polymorphic func prints rather than returns string. Also a bug fix, more readable object initialization, and a rewrite of the introduction.) |
||
Line 499:
Go has a few choices for serialization. The method shown here is the native method, which is compact and type-aware.
A note on object oriented stuff,
<lang go>package main
Line 507:
"os"
)
type printable interface {
print()
}
func main() {
// create instances
animals := []
&
&
&
Color: "yellow",
},▼
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
}},▼
}
Line 520 ⟶ 530:
fmt.Println("created:")
for _, a := range animals {
}
Line 545 ⟶ 555:
return
}
var clones []
gob.NewDecoder(f).Decode(&clones)
if err != nil {
Line 555 ⟶ 565:
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
}
}
type
Alive bool
}
func (a *
if a.Alive {
} else {
}
}
type
ObedienceTrained bool
}
func (d *
▲ }
▲ if d.ObedienceTrained {
default:
▲ return "trained " + r
}
▲ return r + ", not trained"
}
type
LitterBoxTrained bool
}
func (c *
default:
}
▲ if c.LitterBoxTrained {
▲ return "litter box trained " + r
▲ }
▲ return r + ", not litter box trained"
}
type
Color string
}
func (l *
if l.Color == "" {
r
} else {
r = l.Color + " lab"
} ▼
case l.ObedienceTrained:
default:
}
▲ if !l.Alive {
▲ return "dead " + r
▲ }
▲ if l.ObedienceTrained {
▲ return "trained " + r
▲ return r + ", not trained"
}
type
CatchesFrisbee bool
}
func (c *
if !c.Alive {▼
switch {
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
case c.ObedienceTrained && !c.CatchesFrisbee:
case !c.ObedienceTrained && c.CatchesFrisbee:
case !c.ObedienceTrained && !c.CatchesFrisbee:
}
▲ return r
}</lang>
Output:
|