dpo15099 2011-07-11 20:01
浏览 9
已采纳

创建一组扩展类型

I have a struct A, extending ("subclassing") it with struct B, like this:

package main

type A struct {
    x int
}

type B struct {
    A
    y int
}

I want to create a array where I can append A or B to it, so that this code works:

func main() {
    var m [2]B

    m[0] = B { A { 1 }, 2 }
    m[0].x = 0
    m[0].y = 0

    m[1] = A { 3 }
    m[1].x = 0
}

It doesn't. If I create the array of the type B, I get "cannot use struct literal (type A) as type B in assignment". If I try to create the array of the type A, I get the the same error (just with the types reversed).

So my question is: which type should the array be?

  • 写回答

2条回答 默认 最新

  • dousi4257 2011-07-11 21:29
    关注

    You could use struct values. For example,

    package main
    
    import "fmt"
    
    type A struct {
        x int
    }
    
    type B struct {
        A
        y int
    }
    
    func main() {
        var m []interface{}
        m = append(m, B{A{1}, 2})
        m = append(m, A{3})
        fmt.Println(m[0], m[1])
        if b, ok := m[0].(B); ok {
            b.x = 0
            b.y = 0
            m[0] = b
        }
        if a, ok := m[1].(A); ok {
            a.x = 0
            m[1] = a
        }
        fmt.Println(m[0], m[1])
    }
    
    Output:
    {{1} 2} {3}
    {{0} 0} {0}
    

    Or, you could use struct pointers. For example,

    package main
    
    import "fmt"
    
    type A struct {
        x int
    }
    
    type B struct {
        A
        y int
    }
    
    func main() {
        var m []interface{}
        m = append(m, &B{A{1}, 2})
        m = append(m, &A{3})
        fmt.Println(m[0], m[1])
        if b, ok := m[0].(*B); ok {
            b.x = 0
            b.y = 0
        }
        if a, ok := m[1].(*A); ok {
            a.x = 0
        }
        fmt.Println(m[0], m[1])
    }
    
    Output:
    &{{1} 2} &{3}
    &{{0} 0} &{0}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?