Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Interfaces in Go

Tags:

go

thrift

scribe

Fairly new to go. I'm trying to modify this go scribe server implementation:

https://github.com/samuel/go-thrift/blob/master/examples/scribe_server/main.go

I'd like to pass a channel to the Log() func so I can pass scribe data to a separate go routine but I'm not sure how to modify scribe/thrift.go to extend the log interface to be

Log(messages []*scribe.LogEntry, counts chan string)  

(or whether this is even needed and if there is some way to extend the interface without messing with the original library).

like image 842
David Avatar asked Dec 13 '13 01:12

David


People also ask

Can interface implement another interface Golang?

One interface can only extend other interface but cannot implement the other interface as the interface can only have method declarations and not the method body itself.

How do you extend an interface?

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

How are interfaces implemented in Go?

An interface in Go is a type defined using a set of method signatures. The interface defines the behavior for similar type of objects. An interface is declared using the type keyword, followed by the name of the interface and the keyword interface . Then, we specify a set of method signatures inside curly braces.

What happens when you extend an interface?

An interface is a contract without implementations (Java8 introduced default methods). By extending you extend the contract with new "names" to be implemented by concrete class.


1 Answers

You can't modify or extend an already declared interface, you can only create a new one, possibly extending the old one. But you cannot re-declare methods in the interface.

This means that what you want to do (modify the Scribe interface so that its Log method has a different signature) is not possible.

What you can do is to have a type which holds your channel and embeds the structure you want to extend.

Example:

type Scribe interface {
    Log(Messages []*LogEntry) (ResultCode, error)
}

type ModifiedScribe struct {
    Scribe
    counts chan string
}

func (m *ModifiedScribe) Log(Messages []*LogEntry) (ResultCode, error) {
    // do something with m.counts

    // call embedded implementation's Log message
    return m.Scribe.Log(Messages)
}

The example above defines a struct which embeds a Scribe and defines its own Log method, utilizing the one of the embedded Scribe. This struct can be used wherever a Scribe is expected (as it implements the Scribe interface) but holds your additional channel.

like image 111
nemo Avatar answered Sep 27 '22 18:09

nemo