没有名称的Go函数/方法

huangapple go评论75阅读模式
英文:

Go Functions/Methods without a name

问题

我真的很难为我遇到的一种函数找到一个名字。

这是相关的函数:

https://github.com/go-fsnotify/fsnotify/blob/master/fsnotify.go#L32

这是我如何使用它的方式(按照fsnotify的示例):

        select {

            case event := <-watcher.Events:

                log.Println("Event Triggered: ", event)

在这个Println语句中,'event'根据上述函数返回格式化的字符串,我只是不明白为什么直接调用'event'会使用那个函数,而我本来期望它像结构体字段一样被访问(event.Name,event.Op):

event.funcForReturningNicelyFormattedEvent()

感觉这是一个“默认”函数,因为它没有名字,只返回格式化的数据 - 我很难想出名字/类型/搜索术语,以便我可以找到更多信息并更好地理解这个概念和重要性。

感谢任何帮助。

英文:

I'm really struggling to find a name for a type of function I've come across.

Here is the function in question:

https://github.com/go-fsnotify/fsnotify/blob/master/fsnotify.go#L32

This is how I'm using it (as per the fsnotify example):

        select {

            case event := <-watcher.Events:

                log.Println("Event Triggered: ", event)

In that Println 'event' is returning the formatted string as per the function above, I'm just struggling to understand how a straight call to 'event' is using that function yet I would be expecting it to be accessed like the struct fields (event.Name, event.Op):

event.funcForReturningNicelyFormattedEvent()

It feels like this is a 'default' function as it has no name and it just returns the formatted data - I'm struggling to come up with the name/type/search term so I can find out more and understand the concept and importantly the reasoning behind it better.

Any help is appreciated.

答案1

得分: 2

这很简单 - println会自动使用实现了String()方法的任何结构体的String()方法。这是Go语言隐式接口的经典用例:每个具有接口所包含方法的结构体都被认为是实现了该接口。

如果结构体有func String() string方法,它被认为是一个Stringer,并被fmt包使用。当然,你也可以在自己的结构体上使用它。

英文:

It's very simple - println uses the String() method on any struct that implements it automatically. This is a classic use case of Go's implicit interfaces: every struct that has the methods an interface includes, is considered to be implementing the interface.

If it has func String() string it is considered a Stringer and used by fmt. You can use it on your own structs too, of course.

答案2

得分: 1

Println 函数会检查传入的值是否实现了 Stringer 接口。如果实现了,它会调用该值上的 String 方法。在你提供的代码片段中,Event 类型通过提供其自己的 String 方法来实现了该接口。

在 Go 语言中,你不需要声明你实现了接口

英文:

Function Println checks if the passed value implements interface Stringer. If it does it calls method String on this value. Event type implements that interface by supplying its implementation of String method in the excerpt you linked to.

In Go you don't have to declare that you implement interface.

huangapple
  • 本文由 发表于 2014年11月7日 20:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/26801570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定