Struct और Interface
Go Interfaces
Describe behavior as a list of methods. Any type that has them satisfies the interface automatically.
आप क्या सीखेंगे
- Defining an interface
- Implicit implementation
- any and type assertions
interface Shape
ShapeArea(), Name()CircleRect
Behavior, not inheritance
An interface lists methods. Any type that has those methods satisfies the interface automatically: there is no implements keyword. Code written against the interface works with every such type.
Circle and Rect both have Area and Name, so both can be stored in a []Shape and passed to describe. any is the interface with no methods, which every value satisfies. value.(Circle) is a type assertion: ok is true when the value really is a Circle.
मुख्य बातें
- There is no implements keyword.
- A []Shape can hold different types.
value.(Circle)checks the real type.
चलने योग्य Go उदाहरण
main.go
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Name() string
}
type Circle struct{ Radius float64 }
type Rect struct{ Width, Height float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Name() string { return "circle" }
func (r Rect) Area() float64 { return r.Width * r.Height }
func (r Rect) Name() string { return "rectangle" }
func describe(shape Shape) {
fmt.Printf("%s: %.2f\n", shape.Name(), shape.Area())
}
func main() {
shapes := []Shape{Circle{Radius: 1}, Rect{Width: 2, Height: 3.5}}
for _, shape := range shapes {
describe(shape)
}
var value any = shapes[0]
if circle, ok := value.(Circle); ok {
fmt.Println("radius:", circle.Radius)
}
}
circle: 3.14
rectangle: 7.00
radius: 1अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- नोटिफ़िकेशन की लागत ईमेल, SMS और push से संदेश भेजें, जहाँ हर चैनल अपनी लागत खुद गिनता है। आसान
- आकृतियों की फ़ैक्टरी factory का उपयोग करके text descriptions से shapes बनाएँ और हर एक का area लौटाएँ. आसान