Matt Kirwan
Matt Kirwan

Reputation: 21

Go Functions/Methods without a name

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.

Upvotes: 1

Views: 180

Answers (2)

Not_a_Golfer
Not_a_Golfer

Reputation: 49235

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.

Upvotes: 2

Grzegorz Żur
Grzegorz Żur

Reputation: 49221

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.

Upvotes: 1

Related Questions