Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Interfaces in Go | Methods, Interfaces, and Composition
Advanced Go

bookInterfaces in Go

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 1
some-alt