If type T2
is based on type T1
, other than sharing the same data fields, is there any relationship between T1
and T2
?
package main import "fmt" type T1 struct { s string } func (v *T1) F1() string { return v.s } type T2 T1 func (v *T2) F2() string { return v.s } func main() { var t1 = T1{ "xyz" } var t2 = T2{ "pdq" } s0 := t2.F1() // error - expected ok s1 := ((*T1)(&t2)).F1() // ok - expected s2 := ((*T2)(&t1)).F2() // ok - not expected fmt.Println( s0, s1, s2 ) }
My understanding here is lacking
was hoping that T2
would inherit T1
's methods, but such is not the case.
was expecting T2
could be coerced into T1
, since it was derived from T1
was surprised that T1
could be coerced into T2
, but so it is.
it seems that the relationship between T1
and T2
is completely symmetrical - I cannot find anything that breaks the symmetry despite the fact one is actually derived from the other - or is this an illusion?
Go does not support object-oriented type inheritance.
Is Go an object-oriented language?
Why is there no type inheritance?
A method is bound to a single specific type.
A method declaration binds an identifier to a method. The method is said to be bound to the base type and is visible only within selectors for that type.
You can convert between types T1
and T2
.
A value
x
can be converted to typeT
[when]x
's type andT
have identical underlying types.
For example,
package main
import (
"fmt"
)
type T1 struct{ i int }
func (t T1) String() string { return "T1" }
type T2 T1
func (t T2) String() string { return "T2" }
func main() {
t1 := T1{1}
t2 := T2{2}
fmt.Println(t1, t2)
c1 := T1(t2)
c2 := T2(t1)
fmt.Println(c1, c2)
t1 = T1(c2)
t2 = T2(c1)
fmt.Println(t1, t2)
}
Output:
T1 T2
T1 T2
T1 T2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With