alt
codecamp
Golang Essentials: Interfaces
Previous
Next
☰
About
Profile
Account
Login
Sign Up
Logout
Run
Test
Mark Complete
## Interfaces in Go Interfaces in Go are a way to specify the behavior of an object: if something can do "this," it can be used here. ### Defining Interfaces An interface is declared using the `type` keyword, followed by a name and the keyword `interface`: ```go type Shape interface { Area() float64 } ``` ### Implementing Interfaces A type implements an interface by implementing its methods. There is no explicit declaration of intent, no "implements" keyword. ```go type Circle struct { Radius float64 } func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius } ``` In this example, `Circle` implicitly implements the `Shape` interface. ### Using Interfaces Interfaces can be used as function parameters or struct fields, allowing for flexible and decoupled designs. ```go func PrintArea(s Shape) { fmt.Println("Area:", s.Area()) } ``` ### Conclusion Interfaces in Go provide a powerful way to abstract different types behind a set of behaviors, making your code more modular and flexible.