获取密封特征的子类

时间:2015-12-30 17:13:47

标签: scala scala-macros shapeless scala-reflect

是否有可能(通过宏,某种形式的无形自动或其他形式)获得密封特征的子类列表:

  • 在编译时?
  • 在运行时?

1 个答案:

答案 0 :(得分:18)

您不需要任何第三方库来执行此操作:

package main

import "fmt"

type Iface interface {
    Name() string
}

type Strct struct {
    name string
}

func (s Strct) Name() string {
    return s.name
}

func PrintName(i Iface) {
    fmt.Println(i.Name())
}

func main() {
    s := Strct{name: "strct"}
    // Strct implements Iface
    PrintName(s)

    // *Struct implements Iface
    PrintName(&s)

    var si Iface

    // Explicitly setting Iface to Strct works
    si = Strct{name: "Iface from Strct"}
    PrintName(si)

    // Explicitly setting Iface to *Strct works
    si = &Strct{name: "Iface from *Strct"}
    PrintName(si) 

    // Uncomment the next line to see the error when you try to use a pointer to an interface
    //PrintName(&si)
}

输出:

  

对象SubClass1

     

对象SubClass2