Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Interfaces in Go | Methods, Interfaces, and Composition
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Advanced Go

bookInterfaces in Go

Scorri per mostrare il menu

You will explore interfaces in Go. You will learn how to define interfaces, how Go's implicit implementation model works, and how interface values behave at runtime.

Defining Interfaces in Go

In Go, an interface is a type that specifies a set of method signatures. Any type that implements those methods satisfies the interface automatically—there is no need for explicit declaration. This enables you to write flexible and reusable code.

To define an interface, use the type keyword followed by the interface name and the interface keyword. Inside the curly braces, list the method signatures required by the interface.

Here is a simple example:

type Greeter interface {
    Greet() string
}

This code declares a Greeter interface that requires any type to have a Greet method returning a string. Any type with a matching Greet method will satisfy the Greeter interface.

main.go

main.go

copy
1234567891011121314151617181920212223242526
package main import ( "fmt" ) // Speaker defines an interface with a single method type Speaker interface { Speak() string } // Dog struct implicitly implements the Speaker interface type Dog struct { Name string } // Speak method matches the Speaker interface func (d Dog) Speak() string { return "Woof! My name is " + d.Name } func main() { var s Speaker s = Dog{Name: "Buddy"} fmt.Println(s.Speak()) }
question mark

How does a type implement an interface in Go?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 1
some-alt