struct [duplicate]中缺少函数体和字符串标记

问题描述 投票:-2回答:2

这个问题在这里已有答案:

我在Go中找到了一些没有函数体的函数。我知道这意味着Go的外部功能。但是我在哪里可以找到函数boby?

type Creator func(*Beat, *common.Config) (Beater, error)

我还在Go结构中找到一个字符串。这是什么意思?

type BeatConfig struct {
    // output/publishing related configurations
    Output common.ConfigNamespace `config:"output"`
}

所有上述代码都可以在elasticsearch beats中找到:https://github.com/elastic/beats/blob/master/libbeat/beat/beat.go

function elasticsearch go struct syntax
2个回答
1
投票

这个:

type Creator func(*Beat, *common.Config) (Beater, error)

不是function declaration,它是type declaration。它创建一个新类型(函数类型为underlying类型),它不声明任何函数,因此不需要函数体,它没有意义,你不能在那里提供一个体。

例如,您可以使用它来创建该类型的变量,并存储具有相同基础类型的实际函数值。

例:

type Creator func(*Beat, *common.Config) (Beater, error)

func SomeCreator(beat *Beat, config *common.Config) (Beater, error) {
    // Do something
    return nil, nil
}

func main() {
    var mycreator Creator = SomeCreator
    // call it:
    beater, err := mycreator(&Beat{}, &common.Config{})
    // check err, use beater
}

而这个字段声明:

Output common.ConfigNamespace `config:"output"`

包含tag declaration字段的Output。有关更多详细信息,请参阅What are the use(s) for tags in Go?


0
投票

正如@icza所说,Creator是一个type declaration

在您的情况下,Beat的每个实现都实现了Creator接口。这是beats's document

© www.soinside.com 2019 - 2024. All rights reserved.