2021年3月27日星期六

How to get the actual interface type instead of the underlying one, for an interface variable?

Recently i've read an article emphasizing that interfaces are types, not aliases or anything else. Given that, it strikes me as odd that printf's %T verb returns the underlying type and not the interface type as shown in the following lines of code

package main    import (      "fmt"  )    type walker interface {      walk()  }    type person struct {      name string  }    func (p person) walk () {      fmt.Println(p.name, "walked the distance")  }    func main() {      var w walker = person{"Ben"}      w.walk()      fmt.Printf("variable w is of type %T", w)  }  

Any thoughts on why is that? And is there a way to get the actual interface type?

https://stackoverflow.com/questions/66837388/how-to-get-the-actual-interface-type-instead-of-the-underlying-one-for-an-inter March 28, 2021 at 08:24AM

没有评论:

发表评论