Distinguish basic and constraint-only interfaces
Distinguish basic and constraint-only interfaces
A basic interface is described entirely by its method set and can be used as an ordinary value type or as a generic constraint. A non-basic interface may restrict the type set using type terms, unions or comparable. Such an interface is usable only as a constraint or as an element of another constraint interface, not as the type of an ordinary variable.
package main
import ( "fmt")
type Labeler interface{ Label() string }type Item string
func (i Item) Label() string { return string(i) }func show[T Labeler](x T) string { return x.Label() }func main() { var x Labeler = Item("tea") fmt.Println(x.Label(), show(Item("rice")))}Labeler is basic and works in both contexts. The first call uses an interface value; the second uses a type parameter constrained by Labeler. Neither needs explicit registration of Item.
Expected output:
tea riceRestrict allowed underlying types
package main
import ( "fmt")
type Number interface{ ~int | ~int64 }type Score int
func twice[T Number](n T) T { return n + n }func main() { fmt.Println(twice(Score(4)), twice(int64(6)))}Number is not a runtime value type. Its type terms permit addition for all admitted types. A declaration var n Number is invalid. If you need dynamic heterogeneity, use a basic interface or a concrete representation instead.
Expected output:
8 12Try it locally
Define Text interface{~string} and a generic Join[T Text](a,b T) T. Call with a defined Name string type and print the combined value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 06: Distinguish basic and constraint-only interfaces
Check the lesson objective before moving on.
Which can be used as an ordinary variable type?
What is a union of type terms used for?