Embedded struct

前端 未结 2 1683
面向向阳花
面向向阳花 2020-12-17 22:15

Is it possible to inherit methods of a type without using embedded structs?

The first snippet of code is working code that embeds the Property struct in

2条回答
  •  感动是毒
    2020-12-17 22:50

    The short answer to your last question is simply No.

    There is a big difference between type declaration and embedding in golang, you can make your last example working by manually make a type conversion between Node and Properties:

    package main
    
    import "fmt"
    
    type Properties map[string]interface{}
    
    func (p Properties) GetString(key string) string {
        return p[key].(string)
    }
    
    type Nodes map[string]*Node
    
    type Node Properties
    
    func main() {
        allNodes := Nodes{"1": &Node{"test": "foo"}} // :)
        singleNode := allNodes["1"]
        fmt.Println(Properties(*singleNode).GetString("test")) // :D
    }
    

    But it's clearly that is not what you want, you want a struct embedding with a syntax of type aliasing, which is not possible in golang, I think that you should stuck with the your first approach and ignore the the fact the code is redundant and ugly .

提交回复
热议问题