Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a Go interface to another interface?

Tags:

interface

go

I have a Go interface:

type People interface {
    GetName() string
    GetAge() string
}

Now I want another interface Student:

1.

type Student interface {
    GetName() string
    GetAge() string
    GetScore() int
    GetSchoolName() string
}

But I don't want to write the duplicate function GetName and GetAge.

Is there a way to avoid write GetName and GetAge in Student interface ? like:

2.

type Student interface {
    People interface
    GetScore() int
    GetSchoolName() string
}
like image 779
linrongbin Avatar asked Feb 06 '18 13:02

linrongbin


People also ask

Can interface implement another interface Golang?

As we know that the Go language does not support inheritance, but the Go interface fully supports embedding. In embedding, an interface can embed other interfaces or an interface can embed other interface's method signatures in it, the result of both is the same as shown in Example 1 and 2.

What is [] interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

Can interface extend another interface example?

Extending InterfacesAn 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. The following Sports interface is extended by Hockey and Football interfaces.

Can a interface extend inherit another interface?

Yes, we can do it. An interface can extend multiple interfaces in Java.


1 Answers

You can embed interface types. See the Interface type specification

type Student interface {
    People
    GetScore() int
    GetSchoolName() string
}
like image 187
JimB Avatar answered Oct 15 '22 15:10

JimB