types - 如果类型 T2 基于类型 T1,那么从 T1 到 T2 是否有任何类型的 "inheritance"?

标签 types go

如果type T2是基于type T1,除了共享相同的数据字段外,T1之间有什么关系吗>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 )
}

我对这里的了解不足

  1. 希望 T2 继承 T1 的方法,但事实并非如此。

  2. 期望 T2 可以强制转换为 T1,因为它是从 T1

    派生的
  3. 很惊讶 T1 可以强制转换为 T2,但事实就是如此。

  4. 似乎 T1T2 之间的关系是完全对称的——我找不到任何打破对称性的东西,尽管事实上一个是从其他 - 或者这是一种错觉?

最佳答案

Go 不支持面向对象的类型继承。

Is Go an object-oriented language?

Why is there no type inheritance?

一个方法绑定(bind)到一个特定的类型。

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.

您可以 convert T1T2 之间。

A value x can be converted to type T [when] x's type and T have identical underlying types.

例如,

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

关于types - 如果类型 T2 基于类型 T1,那么从 T1 到 T2 是否有任何类型的 "inheritance"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484172/

相关文章:

java - 使用完全限定类型时类型注释抛出 'cannot find symbol'

go - 如何实现接口(interface),但发布新的API?

go - 关系查询

performance - 大型 UTF-8 字符串的快速 fmt.Scanf()

go - 如何在golang中为结构体创建对象

C# 动态类型陷阱

c++ - 微软的edX C++类(class):double vs long double-为什么缺乏通用标准?

c++ - 为什么短裤不应该使用整数文字?

c - fseek 到 32 位无符号偏移量

go - 在 func 中定义本地类型和方法?