Abstract type: Difference between revisions

→‎{{header|Go}}: Rejigged this entry which didn't quite hang together previously.
(→‎{{header|Go}}: Rejigged this entry which didn't quite hang together previously.)
Line 1,096:
 
=={{header|Go}}==
Go's ''interface type'' is an abstract type. It defines a set of methods that a value''concrete type'' must have to satisfy it.
<lang go>interface {
Name() string
SetName(name string)
Method1(value float64) int
}</lang>
 
A variable of an interface type can hold a value of any type that implements the methods that are specified in the interface. You don't need to explicitly "declare" that the type "implements" the interface or anything like that -- the compatibility is purely structural based on the methods.
 
In the following example, the Dog and Cat types both satisfy the Beast interface because they each have the specified methods. The ''bprint'' function can print details for any Beast.
::<lang go>package main
 
<lang go>interfacepackage {main
 
import "fmt"
 
type Beast interface {
Cry Kind() string
Name() string
func (p Pet) Cry() string {
}
 
type PetDog struct {}
kind string
SetName(name string)
 
func (d Dog) Kind() string { return d.kind }
 
func (d Dog) Name() string { return d.name }
 
func (d Dog) Cry() string { return "Woof" }
 
type Cat struct {
kind string
Pet
name string
}
 
func (pc PetCat) NameKind(b Beast) string { return c.kind }
 
fmt.Println(b.Cry())
func (c Cat) Name() string { return c.name }
 
func (p Pet) Cry() string {
func (c Cat) Cry() string { return "WoofMeow" }
 
}
func bprint(cb CatBeast) Cry() string {
fmt.Printf("%s, who's a %s, cries: %q.\n", b.Name(), b.Kind(), b.Cry())
return "Meow"
}
 
func main() {
d := Dog{"labrador", "Max"}
p := Pet{}
c := Cat{"siamese", "Sammy"}
bprint(d)
p.Name(p) // prt Woof
bprint(c)
c.Name(c) // prt Meow
}</lang>
 
{{out}}
<pre>
Max, who's a labrador, cries: "Woof".
Sammy, who's a siamese, cries: "Meow".
</pre>
 
=={{header|Groovy}}==
9,476

edits