Sealed classes and methods: Difference between revisions
→{{header|Go}}: Now uses the C entry's idea of passing a type identifier.
(→{{header|C}}: Simplified code a bit.) |
(→{{header|Go}}: Now uses the C entry's idea of passing a type identifier.) |
||
Line 122:
Consequently, a Go struct and its methods are effectively sealed unless the struct is embedded in another one. However, the only way to prevent embedding from outside the package would be to make the struct private to its package which may not be an acceptable solution unless it and/or its methods could be exposed indirectly.
Fortunately, as the following example shows, the Wren technique for sealing methods can still be used provided we pass a further parameter (a type identifier) to the method so that it knows whether its being called with a pointer to a 'parent' or to a 'child' instance. This information is needed because the type system is such that the runtime type of the receiver will always be 'parent'.
<syntaxhighlight lang="go">package main
import "fmt"
type typeid int
const (
PARENT typeid = iota
CHILD
)
type parent struct {
Line 138 ⟶ 143:
}
func (p *parent) watchMovie(id typeid) {
fmt.Printf("Sorry, %s, you are too young to watch the movie.\n", p.name)
} else {
Line 148 ⟶ 152:
func main() {
p := &parent{"Donald", 42}
p.watchMovie(PARENT)
c1 := &child{parent{"Lisa", 18}}
c2 := &child{parent{"Fred", 10}}
c1.watchMovie(CHILD)
c2.watchMovie(CHILD)
}</syntaxhighlight>
{{out}}
<pre>
Donald is watching the movie...
Lisa is watching the movie...
Sorry, Fred, you are too young to watch the movie.
</pre>
|