go - 嵌入式结构

标签 go

是否可以在不使用嵌入式结构的情况下继承一种类型的方法?

第一段代码是在 Node 中嵌入 Property 结构的工作代码,我可以调用 node.GetString Properties 的方法。我不喜欢的一点是,当我初始化 Node 时,我有(?)初始化其中的 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 struct {
    *Properties
}

func main() {
    allNodes := Nodes{"1": &Node{&Properties{"test": "foo"}}} // :'(
    singleNode := allNodes["1"]
    fmt.Println(singleNode.GetString("test"))
}

最终,我想做如下的事情。其中 Node 是类型 Properties 并且初始化也不需要初始化 Property 结构。以下代码不起作用,但可能很清楚我的目标是什么。

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(singleNode.GetString("test")) // :D
}

我将添加更多将使用 Properties 方法的结构,这就是我要问的原因。如果我只有 Node,我就只有 Node 的方法就可以了。但是因为我将拥有的不仅仅是 Node,我发现向所有嵌入 Properties

的结构添加相同的方法有点多余

我想更多的是确切的问题,我想使用 Node 中的 Properties 方法,而不必初始化 Properties

最佳答案

所以您在这里遇到了 Go 的特性。嵌入是一个结构的方法可以“提升”为似乎存在于另一个结构上的唯一方法。虽然 type Node Properties 应该公开 Node 上的 Properties 方法感觉很直观,但该语法的效果是针对 Node 采用 Properties 的内存布局,但不采用其任何方法。

它没有解释为什么做出这种设计选择,而是解释了 Go Spec如果干燥,至少是特定的。如果您完全照原样阅读,没有任何解释,那么它是非常准确的:

The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T

GetString 有一个类型为 Properties 的接收器,而不是 Node,说真的,解释规范就像你是一个没有想象力的会计师。话虽如此:

Further rules apply to structs containing anonymous fields, as described in the section on struct types.

...

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

Given a struct type S and a type named T, promoted methods are included in the method set of the struct as follows:

  • If S contains an anonymous field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
  • If S contains an anonymous field *T, the method sets of S and *S both include promoted methods with receiver T or *T.

关于复合字面量的那一行是强制您在创建的每个 Node 中声明 Properties 的东西。

附注嗨,杰夫!

关于go - 嵌入式结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079466/

相关文章:

go - golang编译器/设置路径问题

go - 监控 Go 中任何 channel 的完整性

mongodb - Golang使用MongoDB报告 "context deadline exceeded"

go - 在 Go gRPC 处理程序中从客户端证书获取主题 DN

go - 解决 goroutines 死锁

xml - 将 XML 解码到映射中

go - Go 中 slice 排序的意外基准测试结果

unit-testing - 导出 Golang 包进行测试?

performance - 为什么这个 Go 代码的速度与 Python 的速度相当(而且快不了多少)?

pointers - 将 uintptr 从反射转换为指针 (*)