{"id":1052,"date":"2026-08-16T19:04:44","date_gmt":"2026-08-16T19:04:44","guid":{"rendered":"https:\/\/www.devopsschool.com\/tutorials\/?p=1052"},"modified":"2026-08-17T08:12:16","modified_gmt":"2026-08-17T08:12:16","slug":"go-tutorial-go-interfaces","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/tutorials\/go-tutorial-go-interfaces\/","title":{"rendered":"Go Tutorial: Go Interfaces"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">These three concepts are confusing initially because <strong>a method looks almost exactly like a function<\/strong>. The easiest way is to learn them in this order:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Function \u2192 Struct \u2192 Method \u2192 Interface<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Forget interfaces for a moment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Function = a standalone piece of work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You already know this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc add(a int, b int) int {\n    return a + b\n}\n\nfunc main() {\n    result := add(10, 20)\n    fmt.Println(result)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func add(a int, b int) int<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">means:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func     add       (a int, b int)     int\n \u2193        \u2193              \u2193             \u2193\nfunction name         inputs       return type<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And you call it directly:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>add(10, 20)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Think:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Function = independent action.<\/p>\n<\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">2. Struct = an object\/data type<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now suppose we&#8217;re making a <code>Person<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Person struct {\n    Name string\n    Age  int\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p := Person{\n    Name: \"Rajesh\",\n    Age:  42,\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We have:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Person\n \u251c\u2500\u2500 Name\n \u2514\u2500\u2500 Age<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">But currently the Person only has <strong>data<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What if we want the Person to perform an action?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s where a <strong>method<\/strong> comes in.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">3. Method = function attached to a type<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Person struct {\n    Name string\n}\n\nfunc (p Person) sayHello() {\n    fmt.Println(\"Hello, my name is\", p.Name)\n}\n\nfunc main() {\n    p := Person{Name: \"Rajesh\"}\n\n    p.sayHello()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Hello, my name is Rajesh<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Look carefully at this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (p Person) sayHello() {<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Compare it with a normal function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func sayHello() {<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The only important difference is this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(p Person)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s called the <strong>receiver<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It means:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><code>sayHello()<\/code> belongs to <code>Person<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore we call it like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p.sayHello()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">rather than:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sayHello()<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">4. Function vs Method<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">This is the key distinction.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Function<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func add(a int, b int) int {\n    return a + b\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Call:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>add(10, 20)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Method<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func (p Person) sayHello() {\n    fmt.Println(p.Name)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Call:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>p.sayHello()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FUNCTION\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nadd(10, 20)\n \u2191\nstandalone\n\n\nMETHOD\n\u2500\u2500\u2500\u2500\u2500\u2500\n\np.sayHello()\n\u2191    \u2191\n|    method\n|\nPerson object<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The easiest rule:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>A method is basically a function attached to a type.<\/strong><\/p>\n<\/blockquote>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">5. One example with both Function and Method<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Person struct {\n    Name string\n    Age  int\n}\n\n\/\/ Normal function\nfunc add(a int, b int) int {\n    return a + b\n}\n\n\/\/ Method of Person\nfunc (p Person) introduce() {\n    fmt.Println(\"My name is\", p.Name)\n}\n\nfunc main() {\n\n    result := add(10, 20)\n    fmt.Println(result)\n\n    p := Person{\n        Name: \"Rajesh\",\n        Age:  42,\n    }\n\n    p.introduce()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There are now two different things:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>add()\n  \u2502\n  \u2514\u2500\u2500 normal function\n\n\nPerson\n  \u2502\n  \u2514\u2500\u2500 introduce()\n        \u2502\n        \u2514\u2500\u2500 method<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">6. Why use methods at all?<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type BankAccount struct {\n    Balance float64\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Actions related to a bank account naturally belong to the account:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>account.Deposit(1000)\naccount.Withdraw(500)\naccount.ShowBalance()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of writing:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>deposit(account, 1000)\nwithdraw(account, 500)\nshowBalance(account)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go lets us associate behavior with the type.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype BankAccount struct {\n    Balance float64\n}\n\nfunc (a BankAccount) showBalance() {\n    fmt.Println(\"Balance:\", a.Balance)\n}\n\nfunc main() {\n\n    account := BankAccount{\n        Balance: 5000,\n    }\n\n    account.showBalance()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Think:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>BankAccount\n     \u2502\n     \u251c\u2500\u2500 Balance      \u2190 data\n     \u2502\n     \u2514\u2500\u2500 showBalance  \u2190 behavior\/method<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now methods should hopefully make sense.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">7. NOW interface<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Interface sounds complicated, but its basic idea is simple:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>An interface says which methods something must have.<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">It doesn&#8217;t contain the actual implementation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Speaker interface {\n    Speak()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This says:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Anything having a <code>Speak()<\/code> method can be considered a <code>Speaker<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s it.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">10 practical use cases of interfaces in Go<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>#<\/th><th>Use case<\/th><th>Why use an interface?<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td><strong>Payment methods<\/strong><\/td><td>Support Credit Card, UPI, PayPal, etc. through the same API<\/td><\/tr><tr><td>2<\/td><td><strong>Database \/ Repository<\/strong><\/td><td>Switch MySQL, PostgreSQL, memory storage, etc. without changing business logic<\/td><\/tr><tr><td>3<\/td><td><strong>Logging<\/strong><\/td><td>Switch console, file, Datadog, CloudWatch, etc.<\/td><\/tr><tr><td>4<\/td><td><strong>Notifications<\/strong><\/td><td>Handle Email, SMS, Push notifications uniformly<\/td><\/tr><tr><td>5<\/td><td><strong>File\/Storage systems<\/strong><\/td><td>Switch local disk, S3, GCS, Azure Blob<\/td><\/tr><tr><td>6<\/td><td><strong>Testing \/ Mocking<\/strong><\/td><td>Replace real external systems with fake implementations<\/td><\/tr><tr><td>7<\/td><td><strong>Authentication providers<\/strong><\/td><td>Support Google, GitHub, LDAP, Keycloak, etc.<\/td><\/tr><tr><td>8<\/td><td><strong>Message queues<\/strong><\/td><td>Switch Kafka, RabbitMQ, SQS, etc.<\/td><\/tr><tr><td>9<\/td><td><strong>Different shapes\/types with common behavior<\/strong><\/td><td>Circle, Rectangle, Triangle can all implement <code>Area()<\/code><\/td><\/tr><tr><td>10<\/td><td><strong>Standard-library interoperability<\/strong><\/td><td>Implement interfaces such as <code>io.Reader<\/code>, <code>io.Writer<\/code>, <code>error<\/code>, <code>fmt.Stringer<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Interface \u2192 WHAT you can do<br>Struct \u2192 WHAT you are \/ what data you have<br>Method \u2192 HOW you do something<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">API Gateway<br>\u2193<br>Provides one common entry point<br>\u2193<br>Different backend services<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go Interface<br>\u2193<br>Provides one common contract<br>\u2193<br>Different implementations<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">8. Simple interface example<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a Dog:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Dog struct {\n    Name string\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Give Dog a method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (d Dog) Speak() {\n    fmt.Println(\"Woof!\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now create an interface:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Speaker interface {\n    Speak()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Dog has:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Speak()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">and Speaker requires:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Speak()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Dog satisfies Speaker<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You don&#8217;t need to write:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Dog implements Speaker<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">anywhere.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go figures it out automatically.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">9. Complete example<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Speaker interface {\n    Speak()\n}\n\ntype Dog struct {\n    Name string\n}\n\nfunc (d Dog) Speak() {\n    fmt.Println(d.Name, \"says Woof!\")\n}\n\nfunc main() {\n\n    dog := Dog{\n        Name: \"Tommy\",\n    }\n\n    dog.Speak()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">So far the interface isn&#8217;t doing anything useful.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now watch this.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">10. Another type can implement the same interface<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Person:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Person struct {\n    Name string\n}\n\nfunc (p Person) Speak() {\n    fmt.Println(p.Name, \"says Hello!\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Dog\n \u2514\u2500\u2500 Speak()\n\nPerson\n \u2514\u2500\u2500 Speak()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both have <code>Speak()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Therefore both satisfy:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Speaker interface {\n    Speak()\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">11. This is where interface becomes useful<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Create a function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func makeSpeak(s Speaker) {\n    s.Speak()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>s Speaker<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function doesn&#8217;t ask for:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Dog<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">and doesn&#8217;t ask for:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Person<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It says:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Give me <strong>anything capable of speaking<\/strong>.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Complete program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Speaker interface {\n    Speak()\n}\n\ntype Dog struct {\n    Name string\n}\n\nfunc (d Dog) Speak() {\n    fmt.Println(d.Name, \"says Woof!\")\n}\n\ntype Person struct {\n    Name string\n}\n\nfunc (p Person) Speak() {\n    fmt.Println(p.Name, \"says Hello!\")\n}\n\nfunc makeSpeak(s Speaker) {\n    s.Speak()\n}\n\nfunc main() {\n\n    dog := Dog{Name: \"Tommy\"}\n    person := Person{Name: \"Rajesh\"}\n\n    makeSpeak(dog)\n    makeSpeak(person)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Tommy says Woof!\nRajesh says Hello!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is the important part:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>makeSpeak(dog)\nmakeSpeak(person)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Same function accepts completely different types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because both have:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Speak()<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">12. Visualize the relationship<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>                Speaker interface\n                \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n                \u2502   Speak()    \u2502\n                \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                       \u2502\n             requires Speak()\n                       \u2502\n             \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n             \u2502                   \u2502\n            Dog                Person\n             \u2502                   \u2502\n         Speak()             Speak()\n             \u2502                   \u2502\n          \"Woof\"              \"Hello\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The interface doesn&#8217;t care <strong>how<\/strong> they speak.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It only cares:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Do you have Speak()?<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If yes \u2192 accepted.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">13. Real-world analogy<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Think about a <strong>USB port<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The USB port defines a contract:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>USB Device\n    \u2502\n    \u2514\u2500\u2500 connect()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Many devices can satisfy it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Keyboard \u2500\u2500\u2192 connect()\nMouse    \u2500\u2500\u2192 connect()\nCamera   \u2500\u2500\u2192 connect()\nDrive    \u2500\u2500\u2192 connect()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The computer doesn&#8217;t care whether it&#8217;s:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>keyboard\nmouse\ncamera\ndisk<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It cares that it follows the required interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Go interfaces work similarly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">14. Function, Method and Interface together<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the mental model I recommend memorizing:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FUNCTION\n========\n\nfunc add(a, b int) int\n\nCalled:\n\nadd(10, 20)\n\nMeaning:\n\"Do some work\"\n\n\nMETHOD\n======\n\nfunc (p Person) Speak()\n\nCalled:\n\np.Speak()\n\nMeaning:\n\"Person can do this\"\n\n\nINTERFACE\n=========\n\ntype Speaker interface {\n    Speak()\n}\n\nMeaning:\n\"I accept anything that can Speak()\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s essentially the entire relationship.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\">The easiest way to understand an interface is to see the <strong>same problem without and with an interface<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose we have an application that sends notifications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Without Interface<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We create an email sender:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Email struct{}\n\nfunc (e Email) Send(message string) {\n\tfmt.Println(\"Email:\", message)\n}\n\nfunc Notify(email Email, message string) {\n\temail.Send(message)\n}\n\nfunc main() {\n\temail := Email{}\n\n\tNotify(email, \"Server is down\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func Notify(email Email, message string)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Notify()<\/code> specifically requires an <code>Email<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now suppose tomorrow we introduce SMS:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type SMS struct{}\n\nfunc (s SMS) Send(message string) {\n\tfmt.Println(\"SMS:\", message)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We <strong>cannot<\/strong> do this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sms := SMS{}\n\nNotify(sms, \"Server is down\") \/\/ \u274c ERROR<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Why?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because <code>Notify()<\/code> says:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func Notify(email Email, message string)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It requires specifically:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Email<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">not <code>SMS<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So we may start creating separate functions:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func NotifyEmail(email Email, message string) {\n\temail.Send(message)\n}\n\nfunc NotifySMS(sms SMS, message string) {\n\tsms.Send(message)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Later:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Email\nSMS\nWhatsApp\nSlack\nPush Notification<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Our code becomes increasingly tied to specific types.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">With Interface<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s define the <strong>behavior we actually need<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Sender interface {\n\tSend(message string)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This says:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Give me anything that has a <code>Send(string)<\/code> method.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Complete example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Interface defines the required behavior.\ntype Sender interface {\n\tSend(message string)\n}\n\n\/\/ Email implementation\ntype Email struct{}\n\nfunc (e Email) Send(message string) {\n\tfmt.Println(\"Email:\", message)\n}\n\n\/\/ SMS implementation\ntype SMS struct{}\n\nfunc (s SMS) Send(message string) {\n\tfmt.Println(\"SMS:\", message)\n}\n\n\/\/ Notify does NOT care whether it receives\n\/\/ Email, SMS, WhatsApp, etc.\n\/\/\n\/\/ It only cares that the value can Send().\nfunc Notify(sender Sender, message string) {\n\tsender.Send(message)\n}\n\nfunc main() {\n\n\temail := Email{}\n\tsms := SMS{}\n\n\tNotify(email, \"Server is down\")\n\tNotify(sms, \"Server is down\")\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Email: Server is down\nSMS: Server is down<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The important change is just this:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Without interface<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func Notify(sender Email, message string)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Means:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Give me an Email.<\/strong><\/p>\n<\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">With interface<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func Notify(sender Sender, message string)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Means:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Give me anything that can Send().<\/strong><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s the heart of interfaces.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>WITHOUT INTERFACE\n\nNotify()\n   \u2502\n   \u2502 requires exact type\n   \u2193\n Email\n\n\nWITH INTERFACE\n\n             Sender\n          Send(string)\n              \u2502\n       \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n       \u2193      \u2193      \u2193\n     Email   SMS   WhatsApp\n       \u2502      \u2502      \u2502\n       \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n              \u2193\n           Notify()<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Without interface<\/th><th>With interface<\/th><\/tr><\/thead><tbody><tr><td>Depends on exact type<\/td><td>Depends on behavior<\/td><\/tr><tr><td><code>Notify(Email)<\/code><\/td><td><code>Notify(Sender)<\/code><\/td><\/tr><tr><td>Only <code>Email<\/code> works<\/td><td>Any <code>Sender<\/code> works<\/td><\/tr><tr><td>Harder to extend<\/td><td>Easier to extend<\/td><\/tr><tr><td>More tightly coupled<\/td><td>More flexible<\/td><\/tr><tr><td><code>SMS<\/code> cannot be passed<\/td><td><code>SMS<\/code> can be passed if it has <code>Send()<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">One sentence to remember<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Without interface:<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u201cI need an <code>Email<\/code>.\u201d<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>With interface:<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\u201cI don&#8217;t care whether you&#8217;re Email, SMS, or something else \u2014 if you can <code>Send()<\/code>, I can use you.\u201d<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">That is probably the simplest mental model for Go interfaces.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">15. Look at the syntax side-by-side<\/h1>\n\n\n\n<h3 class=\"wp-block-heading\">Function<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func hello() {\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Method<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>func (p Person) hello() {\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">See the extra:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(p Person)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s what turns the function into a <strong>method associated with <code>Person<\/code><\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Interface<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>type Speaker interface {\n    Speak()\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice there is no implementation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Speak()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">not:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func Speak() {\n    \/\/ implementation\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">An interface describes <strong>what must exist<\/strong>, not how to do it.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">16. One sentence for each<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Memorize these:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Function<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">A function performs some work.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>add(10, 20)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Method<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">A method is a function attached to a type.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>person.Speak()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Interface<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">An interface defines methods that a type must provide.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>type Speaker interface {\n    Speak()\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">17. Don&#8217;t learn interfaces too deeply yet<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">At your current stage, I would learn Go in this sequence:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1. Variables\n      \u2193\n2. if \/ switch\n      \u2193\n3. for \/ range\n      \u2193\n4. Functions\n      \u2193\n5. Struct\n      \u2193\n6. Methods\n      \u2193\n7. Pointers\n      \u2193\n8. Interfaces\n      \u2193\n9. Error handling\n      \u2193\n10. Goroutines \/ Channels<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In particular, <strong>don&#8217;t try to master interfaces before structs and methods are comfortable<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For now, the most important relationship is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>STRUCT\nPerson\n   \u2502\n   \u2502 gets behavior through\n   \u2193\nMETHOD\nSpeak()\n   \u2502\n   \u2502 method can satisfy\n   \u2193\nINTERFACE\nSpeaker<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And the single most important Go interface rule is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>If your type has all the methods required by an interface,\nit automatically satisfies that interface.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">No <code>implements<\/code> keyword is needed in Go.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. Your First Go Interface<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Speaker is an interface.\n\/\/\n\/\/ An interface describes BEHAVIOR.\n\/\/\n\/\/ Speaker says:\n\/\/ \"Any type that has a Speak() string method\n\/\/ can be used as a Speaker.\"\ntype Speaker interface {\n\tSpeak() string\n}\n\n\/\/ Dog is a normal concrete struct type.\ntype Dog struct {\n\tName string\n}\n\n\/\/ Speak is a method on Dog.\n\/\/\n\/\/ Because this method has exactly the same signature\n\/\/ required by Speaker:\n\/\/\n\/\/\tSpeak() string\n\/\/\n\/\/ Dog automatically satisfies the Speaker interface.\n\/\/\n\/\/ Go does NOT require:\n\/\/ \"implements Speaker\"\n\/\/\n\/\/ Interface implementation is implicit.\nfunc (d Dog) Speak() string {\n\treturn d.Name + \" says Woof!\"\n}\n\n\/\/ printSpeech accepts Speaker instead of Dog.\n\/\/\n\/\/ Because of this, the function can accept ANY type\n\/\/ that provides:\n\/\/\n\/\/\tSpeak() string\nfunc printSpeech(s Speaker) {\n\tfmt.Println(s.Speak())\n}\n\nfunc main() {\n\t\/\/ Create a concrete Dog value.\n\tdog := Dog{\n\t\tName: \"Buddy\",\n\t}\n\n\t\/\/ Dog satisfies Speaker,\n\t\/\/ so Dog can be passed here.\n\tprintSpeech(dog)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Buddy says Woof!\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">2. One Interface, Multiple Types<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Speaker describes one capability:\n\/\/\n\/\/ \"I can speak.\"\ntype Speaker interface {\n\tSpeak() string\n}\n\n\/\/ Dog is one completely independent type.\ntype Dog struct {\n\tName string\n}\n\n\/\/ Dog satisfies Speaker because Dog has Speak() string.\nfunc (d Dog) Speak() string {\n\treturn d.Name + \": Woof!\"\n}\n\n\/\/ Person is another completely different type.\ntype Person struct {\n\tName string\n}\n\n\/\/ Person also satisfies Speaker.\n\/\/\n\/\/ Notice:\n\/\/ Person and Dog do NOT inherit from each other.\n\/\/\n\/\/ They simply provide the same required behavior.\nfunc (p Person) Speak() string {\n\treturn p.Name + \": Hello!\"\n}\n\n\/\/ Robot is another unrelated type.\ntype Robot struct {\n\tID string\n}\n\n\/\/ Robot also satisfies Speaker.\nfunc (r Robot) Speak() string {\n\treturn r.ID + \": Beep beep!\"\n}\n\n\/\/ announce does not care whether the value is:\n\/\/\n\/\/ - Dog\n\/\/ - Person\n\/\/ - Robot\n\/\/\n\/\/ It only cares that the value can Speak().\nfunc announce(s Speaker) {\n\tfmt.Println(s.Speak())\n}\n\nfunc main() {\n\tdog := Dog{Name: \"Buddy\"}\n\tperson := Person{Name: \"Alice\"}\n\trobot := Robot{ID: \"R2\"}\n\n\tannounce(dog)\n\tannounce(person)\n\tannounce(robot)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Buddy: Woof!\n\t\/\/ Alice: Hello!\n\t\/\/ R2: Beep beep!\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">3. Interface with Multiple Methods<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Animal requires TWO methods.\n\/\/\n\/\/ A type must provide BOTH methods\n\/\/ to satisfy Animal.\ntype Animal interface {\n\tSpeak() string\n\tMove() string\n}\n\ntype Dog struct {\n\tName string\n}\n\n\/\/ First required method.\nfunc (d Dog) Speak() string {\n\treturn d.Name + \" says Woof!\"\n}\n\n\/\/ Second required method.\nfunc (d Dog) Move() string {\n\treturn d.Name + \" is running\"\n}\n\n\/\/ describeAnimal can safely call both methods\n\/\/ because Animal guarantees both exist.\nfunc describeAnimal(a Animal) {\n\tfmt.Println(a.Speak())\n\tfmt.Println(a.Move())\n}\n\nfunc main() {\n\tdog := Dog{Name: \"Buddy\"}\n\n\tdescribeAnimal(dog)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Buddy says Woof!\n\t\/\/ Buddy is running\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">4. Missing a Required Method<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Animal requires both Speak and Move.\ntype Animal interface {\n\tSpeak() string\n\tMove() string\n}\n\ntype Cat struct{}\n\n\/\/ Cat has Speak().\nfunc (Cat) Speak() string {\n\treturn \"Meow\"\n}\n\n\/\/ Cat does NOT have:\n\/\/\n\/\/\tfunc (Cat) Move() string\n\/\/\n\/\/ Therefore Cat does NOT satisfy Animal.\n\nfunc main() {\n\tcat := Cat{}\n\n\t_ = cat\n\n\t\/\/ This would NOT compile:\n\t\/\/\n\t\/\/ var animal Animal = cat\n\t\/\/\n\t\/\/ Compiler reason:\n\t\/\/\n\t\/\/ Cat does not implement Animal\n\t\/\/ because Cat is missing Move().\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">5. Interface Method Signatures Must Match Exactly<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Speaker requires:\n\/\/\n\/\/\tSpeak() string\ntype Speaker interface {\n\tSpeak() string\n}\n\ntype Dog struct{}\n\n\/\/ This method does NOT satisfy Speaker.\n\/\/\n\/\/ Why?\n\/\/\n\/\/ Speaker requires:\n\/\/\n\/\/\tSpeak() string\n\/\/\n\/\/ But Dog provides:\n\/\/\n\/\/\tSpeak(int) string\n\/\/\n\/\/ The parameter list is different.\nfunc (Dog) Speak(volume int) string {\n\tif volume &gt; 5 {\n\t\treturn \"WOOF!\"\n\t}\n\n\treturn \"woof\"\n}\n\nfunc main() {\n\tdog := Dog{}\n\n\t_ = dog\n\n\t\/\/ This would fail:\n\t\/\/\n\t\/\/ var speaker Speaker = dog\n\t\/\/\n\t\/\/ because:\n\t\/\/\n\t\/\/ Speak(int) string\n\t\/\/\n\t\/\/ is not the same method signature as:\n\t\/\/\n\t\/\/ Speak() string\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">6. Storing a Concrete Value Inside an Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Speaker interface {\n\tSpeak() string\n}\n\ntype Dog struct {\n\tName string\n}\n\nfunc (d Dog) Speak() string {\n\treturn \"Woof from \" + d.Name\n}\n\nfunc main() {\n\t\/\/ speaker has STATIC type Speaker.\n\tvar speaker Speaker\n\n\t\/\/ We store a concrete Dog inside it.\n\tspeaker = Dog{\n\t\tName: \"Buddy\",\n\t}\n\n\t\/\/ Conceptually the interface now contains:\n\t\/\/\n\t\/\/ dynamic type  = Dog\n\t\/\/ dynamic value = Dog{Name: \"Buddy\"}\n\t\/\/\n\t\/\/ The variable itself is still typed as Speaker.\n\n\tfmt.Println(speaker.Speak())\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Woof from Buddy\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">7. Practical Use Case: Notification System<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Notifier represents one behavior:\n\/\/\n\/\/ \"I know how to send a notification.\"\n\/\/\n\/\/ The business code does not need to know\n\/\/ HOW the notification is sent.\ntype Notifier interface {\n\tNotify(message string) error\n}\n\n\/\/ EmailNotifier is one implementation.\ntype EmailNotifier struct {\n\tEmail string\n}\n\n\/\/ Notify makes EmailNotifier satisfy Notifier.\nfunc (e EmailNotifier) Notify(message string) error {\n\tfmt.Println(\"EMAIL TO:\", e.Email)\n\tfmt.Println(\"MESSAGE:\", message)\n\n\treturn nil\n}\n\n\/\/ SMSNotifier is another implementation.\ntype SMSNotifier struct {\n\tPhone string\n}\n\n\/\/ Same interface method,\n\/\/ completely different implementation.\nfunc (s SMSNotifier) Notify(message string) error {\n\tfmt.Println(\"SMS TO:\", s.Phone)\n\tfmt.Println(\"MESSAGE:\", message)\n\n\treturn nil\n}\n\n\/\/ sendAlert works with ANY Notifier.\n\/\/\n\/\/ This is the important abstraction:\n\/\/\n\/\/ sendAlert does not depend on EmailNotifier.\n\/\/ sendAlert does not depend on SMSNotifier.\n\/\/\n\/\/ It depends only on:\n\/\/ \"something that can Notify\".\nfunc sendAlert(n Notifier, message string) error {\n\treturn n.Notify(message)\n}\n\nfunc main() {\n\temail := EmailNotifier{\n\t\tEmail: \"alice@example.com\",\n\t}\n\n\tsms := SMSNotifier{\n\t\tPhone: \"+123456789\",\n\t}\n\n\t_ = sendAlert(email, \"Server is down\")\n\t_ = sendAlert(sms, \"Server is down\")\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">8. Practical Use Case: Payment Processing<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ PaymentProcessor defines what checkout needs.\n\/\/\n\/\/ Checkout does not care whether payment is handled by:\n\/\/\n\/\/ - credit card\n\/\/ - bank\n\/\/ - wallet\n\/\/ - fake test implementation\n\/\/\n\/\/ It only needs Charge().\ntype PaymentProcessor interface {\n\tCharge(amount float64) error\n}\n\ntype CreditCardProcessor struct{}\n\nfunc (CreditCardProcessor) Charge(amount float64) error {\n\tfmt.Printf(\"Charging credit card: $%.2f\\n\", amount)\n\n\treturn nil\n}\n\ntype BankProcessor struct{}\n\nfunc (BankProcessor) Charge(amount float64) error {\n\tfmt.Printf(\"Charging bank account: $%.2f\\n\", amount)\n\n\treturn nil\n}\n\n\/\/ checkout depends on behavior,\n\/\/ not a specific payment provider.\nfunc checkout(\n\tprocessor PaymentProcessor,\n\tamount float64,\n) error {\n\treturn processor.Charge(amount)\n}\n\nfunc main() {\n\tcard := CreditCardProcessor{}\n\tbank := BankProcessor{}\n\n\t_ = checkout(card, 100)\n\t_ = checkout(bank, 250)\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">9. Value Receiver and Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Reader interface {\n\tRead() string\n}\n\ntype Book struct {\n\tTitle string\n}\n\n\/\/ Read uses a VALUE receiver:\n\/\/\n\/\/\t(b Book)\n\/\/\n\/\/ Therefore the method belongs to the method set\n\/\/ needed for Book values.\n\/\/\n\/\/ A *Book can also use value-receiver methods.\nfunc (b Book) Read() string {\n\treturn \"Reading \" + b.Title\n}\n\nfunc printReading(r Reader) {\n\tfmt.Println(r.Read())\n}\n\nfunc main() {\n\t\/\/ Concrete value.\n\tbookValue := Book{\n\t\tTitle: \"Learning Go\",\n\t}\n\n\t\/\/ Pointer to concrete value.\n\tbookPointer := &amp;Book{\n\t\tTitle: \"Advanced Go\",\n\t}\n\n\t\/\/ Both work because Read uses a value receiver.\n\tprintReading(bookValue)\n\tprintReading(bookPointer)\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">10. Pointer Receiver and Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Saver interface {\n\tSave()\n}\n\ntype Document struct {\n\tName string\n}\n\n\/\/ Save uses a POINTER receiver:\n\/\/\n\/\/\t(d *Document)\n\/\/\n\/\/ Therefore *Document satisfies Saver.\n\/\/\n\/\/ Plain Document does NOT have this pointer-receiver\n\/\/ method in its method set for interface satisfaction.\nfunc (d *Document) Save() {\n\tfmt.Println(\"Saving:\", d.Name)\n}\n\nfunc main() {\n\t\/\/ Pointer value.\n\tdocument := &amp;Document{\n\t\tName: \"report.txt\",\n\t}\n\n\t\/\/ This works because *Document satisfies Saver.\n\tvar saver Saver = document\n\n\tsaver.Save()\n\n\t\/\/ This would NOT compile:\n\t\/\/\n\t\/\/ var saver2 Saver = Document{\n\t\/\/     Name: \"notes.txt\",\n\t\/\/ }\n\t\/\/\n\t\/\/ Reason:\n\t\/\/\n\t\/\/ Save() is defined on *Document,\n\t\/\/ not on Document.\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">11. Direct Method Calls vs Interface Method Sets<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Saver interface {\n\tSave()\n}\n\ntype File struct {\n\tName string\n}\n\n\/\/ Pointer receiver.\nfunc (f *File) Save() {\n\tfmt.Println(\"Saving:\", f.Name)\n}\n\nfunc main() {\n\t\/\/ file is a normal value.\n\tfile := File{\n\t\tName: \"data.txt\",\n\t}\n\n\t\/\/ This works.\n\t\/\/\n\t\/\/ Because file is addressable,\n\t\/\/ Go can automatically treat this approximately like:\n\t\/\/\n\t\/\/ (&amp;file).Save()\n\tfile.Save()\n\n\t\/\/ But this is a DIFFERENT question:\n\t\/\/\n\t\/\/ Does File satisfy Saver?\n\t\/\/\n\t\/\/ No.\n\t\/\/\n\t\/\/ *File satisfies Saver.\n\t\/\/\n\t\/\/ Therefore this works:\n\tvar saver Saver = &amp;file\n\n\tsaver.Save()\n\n\t\/\/ But this would fail:\n\t\/\/\n\t\/\/ var wrong Saver = file\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">12. Method-Set Rule<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Reader requires Read().\ntype Reader interface {\n\tRead()\n}\n\n\/\/ Writer requires Write().\ntype Writer interface {\n\tWrite()\n}\n\ntype User struct{}\n\n\/\/ Value receiver.\n\/\/\n\/\/ Conceptually:\n\/\/\n\/\/ User has Read()\n\/\/ *User also has Read()\nfunc (User) Read() {}\n\n\/\/ Pointer receiver.\n\/\/\n\/\/ Conceptually:\n\/\/\n\/\/ *User has Write()\n\/\/\n\/\/ Plain User does not satisfy an interface\n\/\/ requiring Write().\nfunc (*User) Write() {}\n\nfunc main() {\n\tuser := User{}\n\n\t\/\/ User satisfies Reader.\n\tvar r1 Reader = user\n\n\t\/\/ *User also satisfies Reader.\n\tvar r2 Reader = &amp;user\n\n\t\/\/ *User satisfies Writer.\n\tvar w1 Writer = &amp;user\n\n\t_, _, _ = r1, r2, w1\n\n\t\/\/ This would fail:\n\t\/\/\n\t\/\/ var w2 Writer = user\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">13. Compile-Time Interface Check<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype Notifier interface {\n\tNotify(string) error\n}\n\ntype EmailNotifier struct{}\n\nfunc (*EmailNotifier) Notify(message string) error {\n\treturn nil\n}\n\n\/\/ This line performs a compile-time interface check.\n\/\/\n\/\/ It asks:\n\/\/\n\/\/ \"Does *EmailNotifier satisfy Notifier?\"\n\/\/\n\/\/ The blank identifier _ means:\n\/\/\n\/\/ \"We don't need to store this value.\"\n\/\/\n\/\/ If EmailNotifier stops satisfying Notifier,\n\/\/ compilation fails immediately.\nvar _ Notifier = (*EmailNotifier)(nil)\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">14. The Empty Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n\t\/\/ interface{} contains ZERO required methods.\n\t\/\/\n\t\/\/ Every normal Go type satisfies an interface\n\t\/\/ with zero method requirements.\n\tvar value interface{}\n\n\tvalue = 100\n\tfmt.Println(value)\n\n\tvalue = \"Hello\"\n\tfmt.Println(value)\n\n\tvalue = true\n\tfmt.Println(value)\n\n\tvalue = &#91;]int{1, 2, 3}\n\tfmt.Println(value)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ 100\n\t\/\/ Hello\n\t\/\/ true\n\t\/\/ &#91;1 2 3]\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">15. <code>any<\/code><\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ any is an alias for interface{}.\n\/\/\n\/\/ These are equivalent:\n\/\/\n\/\/\tvar x interface{}\n\/\/\n\/\/\tvar x any\n\/\/\n\/\/ In modern Go code, any is usually easier to read\n\/\/ when arbitrary values are genuinely needed.\nfunc printAnything(value any) {\n\tfmt.Println(value)\n}\n\nfunc main() {\n\tprintAnything(10)\n\tprintAnything(\"Go\")\n\tprintAnything(true)\n\tprintAnything(3.14)\n\tprintAnything(&#91;]string{\"A\", \"B\"})\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">16. Do Not Use <code>any<\/code> When a Better Type Exists<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ This function is clear.\n\/\/\n\/\/ The compiler knows exactly what goes in\n\/\/ and exactly what comes out.\nfunc addGood(a, b int) int {\n\treturn a + b\n}\n\n\/\/ This design would be much harder to understand:\n\/\/\n\/\/\tfunc addBad(a, b any) any\n\/\/\n\/\/ Problems:\n\/\/\n\/\/ 1. What types are allowed?\n\/\/ 2. What type is returned?\n\/\/ 3. What happens for strings?\n\/\/ 4. What happens for structs?\n\/\/ 5. Errors move from compile time toward runtime.\n\/\/\n\/\/ Use any only when arbitrary types are actually part\n\/\/ of the problem you are solving.\n\nfunc main() {\n\tresult := addGood(10, 20)\n\n\t_ = result\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">17. Type Assertion<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n\t\/\/ value has static type any.\n\t\/\/\n\t\/\/ Its dynamic type is string.\n\tvar value any = \"Hello Go\"\n\n\t\/\/ Type assertion syntax:\n\t\/\/\n\t\/\/\tinterfaceValue.(ConcreteType)\n\t\/\/\n\t\/\/ Here we are saying:\n\t\/\/\n\t\/\/ \"Give me the string stored inside value.\"\n\ttext := value.(string)\n\n\tfmt.Println(text)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Hello Go\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">18. Unsafe Type Assertion<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nfunc main() {\n\tvar value any = 100\n\n\t\/\/ value contains an int.\n\t\/\/\n\t\/\/ Therefore this assertion would panic:\n\t\/\/\n\t\/\/ text := value.(string)\n\t\/\/\n\t\/\/ Runtime reason:\n\t\/\/\n\t\/\/ value contains int,\n\t\/\/ but we demanded string.\n\n\t_ = value\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">19. Safe Type Assertion<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar value any = \"Hello\"\n\n\t\/\/ Two-value type assertion:\n\t\/\/\n\t\/\/\ttext, ok := value.(string)\n\t\/\/\n\t\/\/ text receives the value if successful.\n\t\/\/\n\t\/\/ ok becomes true when successful.\n\t\/\/\n\t\/\/ This avoids a panic.\n\ttext, ok := value.(string)\n\n\tif !ok {\n\t\tfmt.Println(\"value is not a string\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"String:\", text)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ String: Hello\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">20. Failed Safe Type Assertion<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar value any = 123\n\n\ttext, ok := value.(string)\n\n\t\/\/ Assertion fails.\n\t\/\/\n\t\/\/ ok becomes false.\n\t\/\/\n\t\/\/ text receives string's zero value:\n\t\/\/\n\t\/\/ \"\"\n\tfmt.Printf(\"text = %q\\n\", text)\n\tfmt.Println(\"ok =\", ok)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ text = \"\"\n\t\/\/ ok = false\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">21. Type Switch<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc describe(value any) {\n\t\/\/ value.(type) is special syntax\n\t\/\/ used inside a type switch.\n\tswitch v := value.(type) {\n\n\tcase int:\n\t\t\/\/ Inside this case,\n\t\t\/\/ v is an int.\n\t\tfmt.Println(\"Integer:\", v)\n\n\tcase string:\n\t\t\/\/ Here v is a string.\n\t\tfmt.Println(\"String:\", v)\n\n\tcase bool:\n\t\t\/\/ Here v is a bool.\n\t\tfmt.Println(\"Boolean:\", v)\n\n\tcase float64:\n\t\t\/\/ Here v is a float64.\n\t\tfmt.Println(\"Float:\", v)\n\n\tdefault:\n\t\t\/\/ Any unmatched type arrives here.\n\t\tfmt.Println(\"Unknown type\")\n\t}\n}\n\nfunc main() {\n\tdescribe(10)\n\tdescribe(\"Go\")\n\tdescribe(true)\n\tdescribe(3.14)\n\tdescribe(&#91;]int{1, 2})\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Integer: 10\n\t\/\/ String: Go\n\t\/\/ Boolean: true\n\t\/\/ Float: 3.14\n\t\/\/ Unknown type\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">22. Interface Composition<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Reader describes reading behavior.\ntype Reader interface {\n\tRead() string\n}\n\n\/\/ Writer describes writing behavior.\ntype Writer interface {\n\tWrite(string)\n}\n\n\/\/ ReadWriter embeds both interfaces.\n\/\/\n\/\/ Therefore a value must provide:\n\/\/\n\/\/\tRead() string\n\/\/\tWrite(string)\n\/\/\n\/\/ to satisfy ReadWriter.\ntype ReadWriter interface {\n\tReader\n\tWriter\n}\n\ntype Document struct {\n\tContent string\n}\n\nfunc (d Document) Read() string {\n\treturn d.Content\n}\n\nfunc (d *Document) Write(content string) {\n\td.Content = content\n}\n\nfunc useDocument(rw ReadWriter) {\n\trw.Write(\"Go Interfaces\")\n\n\tfmt.Println(rw.Read())\n}\n\nfunc main() {\n\t\/\/ We use *Document because Write has a pointer receiver.\n\tdocument := &amp;Document{}\n\n\tuseDocument(document)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Go Interfaces\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">23. Small Interfaces<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Small interfaces usually create lower coupling.\n\n\/\/ Reader needs only reading behavior.\ntype Reader interface {\n\tRead() string\n}\n\n\/\/ Writer needs only writing behavior.\ntype Writer interface {\n\tWrite(string)\n}\n\n\/\/ Deleter needs only deletion behavior.\ntype Deleter interface {\n\tDelete() error\n}\n\n\/\/ Instead of forcing every consumer to depend on:\n\/\/\n\/\/ type Everything interface {\n\/\/     Read() string\n\/\/     Write(string)\n\/\/     Delete() error\n\/\/     Export() error\n\/\/     Backup() error\n\/\/     Email() error\n\/\/ }\n\/\/\n\/\/ each consumer can depend only on what it actually needs.\n\nfunc display(r Reader) {\n\t\/\/ display only needs Read().\n\t\/\/\n\t\/\/ Therefore requiring Writer or Deleter here\n\t\/\/ would unnecessarily increase coupling.\n\t_ = r.Read()\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">24. Consumer-Side Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype User struct {\n\tID   int\n\tName string\n}\n\n\/\/ Imagine a real database repository has many methods:\n\/\/\n\/\/ Save\n\/\/ Delete\n\/\/ FindByID\n\/\/ FindByEmail\n\/\/ List\n\/\/ Update\n\/\/ Count\n\/\/\n\/\/ But this service needs only FindByID.\n\/\/\n\/\/ Therefore the consumer can define a tiny interface\n\/\/ containing only what it actually uses.\ntype UserFinder interface {\n\tFindByID(id int) (User, error)\n}\n\ntype UserService struct {\n\tfinder UserFinder\n}\n\nfunc NewUserService(finder UserFinder) *UserService {\n\treturn &amp;UserService{\n\t\tfinder: finder,\n\t}\n}\n\nfunc (s *UserService) GetUser(id int) (User, error) {\n\treturn s.finder.FindByID(id)\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">25. Dependency Injection with Interfaces<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ EmailSender describes the dependency\n\/\/ needed by UserService.\ntype EmailSender interface {\n\tSend(to string, message string) error\n}\n\n\/\/ UserService stores the INTERFACE,\n\/\/ not a specific SMTP implementation.\ntype UserService struct {\n\temailSender EmailSender\n}\n\n\/\/ The dependency is supplied from outside.\n\/\/\n\/\/ This is dependency injection.\n\/\/\n\/\/ No special framework is required.\nfunc NewUserService(\n\tsender EmailSender,\n) *UserService {\n\treturn &amp;UserService{\n\t\temailSender: sender,\n\t}\n}\n\nfunc (s *UserService) Register(email string) error {\n\tfmt.Println(\"Creating user:\", email)\n\n\t\/\/ UserService does not know HOW email is sent.\n\t\/\/\n\t\/\/ It only knows the dependency supports Send().\n\treturn s.emailSender.Send(\n\t\temail,\n\t\t\"Welcome!\",\n\t)\n}\n\n\/\/ Production implementation.\ntype SMTPEmailSender struct{}\n\nfunc (SMTPEmailSender) Send(\n\tto string,\n\tmessage string,\n) error {\n\tfmt.Println(\"SMTP email to:\", to)\n\tfmt.Println(\"Message:\", message)\n\n\treturn nil\n}\n\nfunc main() {\n\tsender := SMTPEmailSender{}\n\n\tservice := NewUserService(sender)\n\n\t_ = service.Register(\"alice@example.com\")\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">26. Testing with a Fake Implementation<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype EmailSender interface {\n\tSend(to string, message string) error\n}\n\ntype UserService struct {\n\tsender EmailSender\n}\n\nfunc NewUserService(sender EmailSender) *UserService {\n\treturn &amp;UserService{\n\t\tsender: sender,\n\t}\n}\n\nfunc (s *UserService) Register(email string) error {\n\treturn s.sender.Send(\n\t\temail,\n\t\t\"Welcome!\",\n\t)\n}\n\n\/\/ FakeEmailSender is used during tests.\n\/\/\n\/\/ Instead of sending a real email,\n\/\/ it records what happened.\ntype FakeEmailSender struct {\n\tCalled  bool\n\tTo      string\n\tMessage string\n}\n\nfunc (f *FakeEmailSender) Send(\n\tto string,\n\tmessage string,\n) error {\n\tf.Called = true\n\tf.To = to\n\tf.Message = message\n\n\treturn nil\n}\n\nfunc main() {\n\t\/\/ Create fake dependency.\n\tfake := &amp;FakeEmailSender{}\n\n\t\/\/ Inject fake dependency.\n\tservice := NewUserService(fake)\n\n\t_ = service.Register(\"alice@example.com\")\n\n\t\/\/ Tests can inspect what happened.\n\tfmt.Println(fake.Called)\n\tfmt.Println(fake.To)\n\tfmt.Println(fake.Message)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ true\n\t\/\/ alice@example.com\n\t\/\/ Welcome!\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">27. Repository Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype User struct {\n\tID   int\n\tName string\n}\n\n\/\/ Business logic depends on this behavior,\n\/\/ not on PostgreSQL\/MySQL\/etc.\ntype UserRepository interface {\n\tSave(user User) error\n\tFindByID(id int) (User, error)\n}\n\n\/\/ MemoryUserRepository is one implementation.\n\/\/\n\/\/ This could be used for:\n\/\/\n\/\/ - learning\n\/\/ - tests\n\/\/ - prototypes\ntype MemoryUserRepository struct {\n\tusers map&#91;int]User\n}\n\nfunc NewMemoryUserRepository() *MemoryUserRepository {\n\treturn &amp;MemoryUserRepository{\n\t\tusers: make(map&#91;int]User),\n\t}\n}\n\nfunc (r *MemoryUserRepository) Save(user User) error {\n\tr.users&#91;user.ID] = user\n\n\treturn nil\n}\n\nfunc (r *MemoryUserRepository) FindByID(\n\tid int,\n) (User, error) {\n\tuser, ok := r.users&#91;id]\n\n\tif !ok {\n\t\treturn User{}, errors.New(\"user not found\")\n\t}\n\n\treturn user, nil\n}\n\nfunc main() {\n\tvar repository UserRepository\n\n\trepository = NewMemoryUserRepository()\n\n\t_ = repository.Save(User{\n\t\tID:   1,\n\t\tName: \"Alice\",\n\t})\n\n\tuser, err := repository.FindByID(1)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\n\tfmt.Println(user.Name)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Alice\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">28. The <code>error<\/code> Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ error is itself an interface.\n\/\/\n\/\/ Conceptually:\n\/\/\n\/\/ type error interface {\n\/\/     Error() string\n\/\/ }\n\/\/\n\/\/ Therefore any type that provides:\n\/\/\n\/\/\tError() string\n\/\/\n\/\/ can be returned as an error.\n\ntype ValidationError struct {\n\tField   string\n\tMessage string\n}\n\n\/\/ By implementing Error() string,\n\/\/ ValidationError satisfies the built-in error interface.\nfunc (e ValidationError) Error() string {\n\treturn e.Field + \": \" + e.Message\n}\n\nfunc validateAge(age int) error {\n\tif age &lt; 18 {\n\t\t\/\/ ValidationError can be returned here\n\t\t\/\/ because it satisfies error.\n\t\treturn ValidationError{\n\t\t\tField:   \"age\",\n\t\t\tMessage: \"must be 18 or older\",\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\terr := validateAge(15)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\n\t\t\/\/ Output:\n\t\t\/\/\n\t\t\/\/ age: must be 18 or older\n\t}\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">29. Standard Interface Example: <code>fmt.Stringer<\/code><\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype User struct {\n\tID   int\n\tName string\n}\n\n\/\/ fmt.Stringer is conceptually:\n\/\/\n\/\/ type Stringer interface {\n\/\/     String() string\n\/\/ }\n\/\/\n\/\/ By implementing String(),\n\/\/ User can control how fmt prints it.\nfunc (u User) String() string {\n\treturn fmt.Sprintf(\n\t\t\"User(ID=%d, Name=%s)\",\n\t\tu.ID,\n\t\tu.Name,\n\t)\n}\n\nfunc main() {\n\tuser := User{\n\t\tID:   1,\n\t\tName: \"Alice\",\n\t}\n\n\tfmt.Println(user)\n\n\t\/\/ Because User satisfies fmt.Stringer,\n\t\/\/ fmt uses user.String().\n\t\/\/\n\t\/\/ Output:\n\t\/\/\n\t\/\/ User(ID=1, Name=Alice)\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">30. Standard Interface Example: <code>io.Reader<\/code><\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\nfunc main() {\n\t\/\/ strings.NewReader returns a value\n\t\/\/ that satisfies io.Reader.\n\treader := strings.NewReader(\n\t\t\"Hello Go Interfaces\",\n\t)\n\n\t\/\/ io.ReadAll does not care that the concrete\n\t\/\/ implementation came from strings.NewReader.\n\t\/\/\n\t\/\/ It accepts io.Reader behavior.\n\tdata, err := io.ReadAll(reader)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\n\tfmt.Println(string(data))\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Hello Go Interfaces\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">31. Why Standard Interfaces Are Powerful<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"strings\"\n)\n\n\/\/ processData accepts io.Reader.\n\/\/\n\/\/ Therefore it can work with many implementations:\n\/\/\n\/\/ - files\n\/\/ - HTTP response bodies\n\/\/ - strings.Reader\n\/\/ - bytes.Buffer\n\/\/ - compressed streams\n\/\/ - network streams\n\/\/\n\/\/ The function needs reading behavior,\n\/\/ not one particular concrete type.\nfunc processData(r io.Reader) error {\n\t_, err := io.ReadAll(r)\n\n\treturn err\n}\n\nfunc main() {\n\t\/\/ strings.Reader satisfies io.Reader.\n\tstringReader := strings.NewReader(\"hello\")\n\n\t_ = processData(stringReader)\n\n\t\/\/ bytes.Buffer also satisfies io.Reader.\n\tbuffer := bytes.NewBufferString(\"hello\")\n\n\t_ = processData(buffer)\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">32. Function Adapter Pattern<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Handler requires a method.\ntype Handler interface {\n\tHandle(message string) error\n}\n\n\/\/ HandlerFunc is a NAMED function type.\ntype HandlerFunc func(string) error\n\n\/\/ By giving HandlerFunc a Handle method,\n\/\/ HandlerFunc satisfies Handler.\nfunc (f HandlerFunc) Handle(\n\tmessage string,\n) error {\n\t\/\/ Call the original function.\n\treturn f(message)\n}\n\n\/\/ This is a normal standalone function.\nfunc printMessage(message string) error {\n\tfmt.Println(message)\n\n\treturn nil\n}\n\nfunc execute(h Handler) error {\n\treturn h.Handle(\"Hello\")\n}\n\nfunc main() {\n\t\/\/ Convert the normal function\n\t\/\/ into HandlerFunc.\n\thandler := HandlerFunc(printMessage)\n\n\t\/\/ HandlerFunc satisfies Handler.\n\t_ = execute(handler)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Hello\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">33. Optional Capability with Type Assertion<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Writer interface {\n\tWrite(string)\n}\n\ntype Flusher interface {\n\tFlush()\n}\n\ntype Buffer struct{}\n\nfunc (Buffer) Write(data string) {\n\tfmt.Println(\"Writing:\", data)\n}\n\nfunc (Buffer) Flush() {\n\tfmt.Println(\"Flushing\")\n}\n\nfunc process(w Writer) {\n\tw.Write(\"Hello\")\n\n\t\/\/ w is guaranteed only to be a Writer.\n\t\/\/\n\t\/\/ But the concrete value MAY also support Flusher.\n\t\/\/\n\t\/\/ This safe interface assertion checks\n\t\/\/ for that optional capability.\n\tif flusher, ok := w.(Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}\n\nfunc main() {\n\tbuffer := Buffer{}\n\n\tprocess(buffer)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Writing: Hello\n\t\/\/ Flushing\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">34. Nil Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Speaker interface {\n\tSpeak()\n}\n\nfunc main() {\n\t\/\/ No concrete type.\n\t\/\/ No concrete value.\n\tvar speaker Speaker\n\n\t\/\/ Conceptually:\n\t\/\/\n\t\/\/ dynamic type  = nil\n\t\/\/ dynamic value = nil\n\t\/\/\n\t\/\/ Therefore the interface itself is nil.\n\tfmt.Println(speaker == nil)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ true\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">35. Typed Nil Inside an Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Speaker interface {\n\tSpeak()\n}\n\ntype Dog struct{}\n\nfunc (*Dog) Speak() {}\n\nfunc main() {\n\t\/\/ dog is a nil pointer.\n\tvar dog *Dog = nil\n\n\t\/\/ Store that typed nil pointer\n\t\/\/ inside an interface.\n\tvar speaker Speaker = dog\n\n\t\/\/ Conceptually speaker contains:\n\t\/\/\n\t\/\/ dynamic type  = *Dog\n\t\/\/ dynamic value = nil\n\t\/\/\n\t\/\/ Because the interface contains type information,\n\t\/\/ the interface itself is NOT nil.\n\tfmt.Println(speaker == nil)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ false\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">36. Typed Nil Error Trap<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype MyError struct {\n\tMessage string\n}\n\n\/\/ Pointer receiver means *MyError satisfies error.\nfunc (e *MyError) Error() string {\n\tif e == nil {\n\t\treturn \"nil MyError\"\n\t}\n\n\treturn e.Message\n}\n\nfunc badFunction() error {\n\t\/\/ err is a nil *MyError pointer.\n\tvar err *MyError\n\n\t\/\/ Returning err puts this inside error:\n\t\/\/\n\t\/\/ dynamic type  = *MyError\n\t\/\/ dynamic value = nil\n\t\/\/\n\t\/\/ Therefore the returned error interface\n\t\/\/ is not nil.\n\treturn err\n}\n\nfunc goodFunction() error {\n\t\/\/ When there is no error,\n\t\/\/ return a true nil interface.\n\treturn nil\n}\n\nfunc main() {\n\terr1 := badFunction()\n\terr2 := goodFunction()\n\n\tfmt.Println(err1 == nil)\n\tfmt.Println(err2 == nil)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ false\n\t\/\/ true\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">37. Interface Adapter for an External API<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Our application wants this interface.\ntype Notifier interface {\n\tNotify(message string) error\n}\n\n\/\/ Imagine this type comes from another package\n\/\/ and we cannot modify it.\ntype ExternalClient struct{}\n\n\/\/ Its method name does not match our interface.\nfunc (ExternalClient) SendMessage(\n\tmessage string,\n) error {\n\tfmt.Println(\"External API:\", message)\n\n\treturn nil\n}\n\n\/\/ Adapter wraps the external client.\ntype NotificationAdapter struct {\n\tclient ExternalClient\n}\n\n\/\/ Adapter translates our application's\n\/\/ Notify() call into the external API's\n\/\/ SendMessage() call.\nfunc (a NotificationAdapter) Notify(\n\tmessage string,\n) error {\n\treturn a.client.SendMessage(message)\n}\n\nfunc sendNotification(n Notifier) error {\n\treturn n.Notify(\"Order completed\")\n}\n\nfunc main() {\n\tclient := ExternalClient{}\n\n\tadapter := NotificationAdapter{\n\t\tclient: client,\n\t}\n\n\t_ = sendNotification(adapter)\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">38. Decorator-Style Interface Composition<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype User struct {\n\tName string\n}\n\ntype UserRepository interface {\n\tSave(User) error\n}\n\n\/\/ Real repository.\ntype MemoryRepository struct{}\n\nfunc (MemoryRepository) Save(user User) error {\n\tfmt.Println(\"Saving:\", user.Name)\n\n\treturn nil\n}\n\n\/\/ LoggingRepository wraps another repository.\ntype LoggingRepository struct {\n\tnext UserRepository\n}\n\n\/\/ Save adds behavior BEFORE and AFTER\n\/\/ delegating to the wrapped repository.\nfunc (r LoggingRepository) Save(\n\tuser User,\n) error {\n\tfmt.Println(\"LOG: Save started\")\n\n\terr := r.next.Save(user)\n\n\tfmt.Println(\"LOG: Save finished\")\n\n\treturn err\n}\n\nfunc main() {\n\trealRepository := MemoryRepository{}\n\n\tloggedRepository := LoggingRepository{\n\t\tnext: realRepository,\n\t}\n\n\t_ = loggedRepository.Save(\n\t\tUser{Name: \"Alice\"},\n\t)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ LOG: Save started\n\t\/\/ Saving: Alice\n\t\/\/ LOG: Save finished\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">39. Interface Segregation<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Bad design for many consumers:\n\/\/\n\/\/ type HugeRepository interface {\n\/\/     FindByID(int) (User, error)\n\/\/     Save(User) error\n\/\/     Delete(int) error\n\/\/     Export() error\n\/\/     Backup() error\n\/\/     Restore() error\n\/\/ }\n\/\/\n\/\/ A consumer that only reads a user\n\/\/ should not need all those methods.\n\ntype User struct {\n\tID int\n}\n\n\/\/ Small interface for reading.\ntype UserFinder interface {\n\tFindByID(int) (User, error)\n}\n\n\/\/ Small interface for saving.\ntype UserSaver interface {\n\tSave(User) error\n}\n\n\/\/ Small interface for deleting.\ntype UserDeleter interface {\n\tDelete(int) error\n}\n\n\/\/ A larger interface can still be composed\n\/\/ when a consumer truly needs everything.\ntype UserRepository interface {\n\tUserFinder\n\tUserSaver\n\tUserDeleter\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">40. Do Not Create Interfaces Too Early<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ This concrete type may be perfectly sufficient\n\/\/ when there is:\n\/\/\n\/\/ - one implementation\n\/\/ - no testing boundary\n\/\/ - no substitution requirement\n\/\/ - no meaningful abstraction yet\ntype Calculator struct{}\n\nfunc (Calculator) Add(a, b int) int {\n\treturn a + b\n}\n\n\/\/ There is no need to automatically create:\n\/\/\n\/\/ type CalculatorInterface interface {\n\/\/     Add(a, b int) int\n\/\/ }\n\/\/\n\/\/ simply because Calculator exists.\n\/\/\n\/\/ Introduce interfaces when they represent\n\/\/ a useful behavioral boundary.\n\nfunc main() {\n\tcalculator := Calculator{}\n\n\tresult := calculator.Add(10, 20)\n\n\t_ = result\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">41. Accept Interface, Return Concrete Type<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype Logger interface {\n\tLog(string)\n}\n\ntype Service struct {\n\tlogger Logger\n}\n\n\/\/ The constructor ACCEPTS an interface.\n\/\/\n\/\/ This allows callers to provide:\n\/\/\n\/\/ - console logger\n\/\/ - file logger\n\/\/ - cloud logger\n\/\/ - fake logger\nfunc NewService(logger Logger) *Service {\n\t\/\/ The constructor RETURNS *Service,\n\t\/\/ a useful concrete type.\n\treturn &amp;Service{\n\t\tlogger: logger,\n\t}\n}\n\nfunc (s *Service) Run() {\n\ts.logger.Log(\"service started\")\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">42. Generic Constraint Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Interfaces are also used as constraints\n\/\/ for generic type parameters.\n\/\/\n\/\/ This interface describes a TYPE SET.\n\/\/\n\/\/ T may have an underlying type matching:\n\/\/\n\/\/ int\n\/\/ int64\n\/\/ float64\ntype Number interface {\n\t~int | ~int64 | ~float64\n}\n\n\/\/ T must satisfy Number.\nfunc Add&#91;T Number](a, b T) T {\n\t\/\/ Addition is allowed because every type\n\t\/\/ permitted by Number supports +.\n\treturn a + b\n}\n\nfunc main() {\n\tfmt.Println(Add(10, 20))\n\tfmt.Println(Add(1.5, 2.5))\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ 30\n\t\/\/ 4\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">43. Why <code>~<\/code> Matters in Generic Interfaces<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ UserID is a custom defined type.\n\/\/\n\/\/ Its underlying type is int.\ntype UserID int\n\n\/\/ ~int means:\n\/\/\n\/\/ \"int OR any defined type whose underlying type is int.\"\ntype Integer interface {\n\t~int\n}\n\nfunc Double&#91;T Integer](value T) T {\n\treturn value * 2\n}\n\nfunc main() {\n\tvar id UserID = 10\n\n\t\/\/ UserID satisfies ~int\n\t\/\/ because its underlying type is int.\n\tresult := Double(id)\n\n\tfmt.Println(result)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ 20\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">44. <code>comparable<\/code> Interface Constraint<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ comparable is a built-in constraint.\n\/\/\n\/\/ T must support:\n\/\/\n\/\/ ==\n\/\/ !=\nfunc Equal&#91;T comparable](a, b T) bool {\n\treturn a == b\n}\n\nfunc main() {\n\tfmt.Println(Equal(10, 10))\n\tfmt.Println(Equal(10, 20))\n\n\tfmt.Println(Equal(\"Go\", \"Go\"))\n\tfmt.Println(Equal(\"Go\", \"Java\"))\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ true\n\t\/\/ false\n\t\/\/ true\n\t\/\/ false\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">45. Generic Set Using <code>comparable<\/code><\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Map keys must be comparable.\n\/\/\n\/\/ Therefore T is constrained by comparable.\ntype Set&#91;T comparable] map&#91;T]struct{}\n\nfunc (s Set&#91;T]) Add(value T) {\n\t\/\/ Empty struct{} takes no meaningful payload space.\n\ts&#91;value] = struct{}{}\n}\n\nfunc (s Set&#91;T]) Contains(value T) bool {\n\t_, ok := s&#91;value]\n\n\treturn ok\n}\n\nfunc main() {\n\tnumbers := Set&#91;int]{}\n\n\tnumbers.Add(10)\n\tnumbers.Add(20)\n\n\tfmt.Println(numbers.Contains(10))\n\tfmt.Println(numbers.Contains(99))\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ true\n\t\/\/ false\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">46. Runtime Interface vs Generic Constraint<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Runtime behavioral interface.\n\/\/\n\/\/ Values can be stored in variables of this interface type.\ntype Speaker interface {\n\tSpeak() string\n}\n\n\/\/ Generic constraint interface.\n\/\/\n\/\/ Its type terms describe what compile-time\n\/\/ generic types are permitted.\ntype Number interface {\n\t~int | ~float64\n}\n\nfunc PrintSpeaker(s Speaker) {\n\t\/\/ Runtime polymorphism:\n\t\/\/\n\t\/\/ the concrete type can vary at runtime.\n\t_ = s.Speak()\n}\n\nfunc Add&#91;T Number](a, b T) T {\n\t\/\/ Compile-time generic reuse:\n\t\/\/\n\t\/\/ the compiler works with the selected T.\n\treturn a + b\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">47. Interfaces vs Generics<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Use an interface when the important question is:\n\/\/\n\/\/ \"What behavior does this value provide?\"\n\ntype Saver interface {\n\tSave() error\n}\n\nfunc persist(s Saver) error {\n\treturn s.Save()\n}\n\n\/\/ Use generics when the important question is:\n\/\/\n\/\/ \"Can this algorithm work with many compile-time types?\"\n\nfunc First&#91;T any](values &#91;]T) T {\n\treturn values&#91;0]\n}\n\n\/\/ Interfaces and generics are not competitors.\n\/\/\n\/\/ Interfaces:\n\/\/ - behavior abstraction\n\/\/ - runtime polymorphism\n\/\/ - dependency boundaries\n\/\/\n\/\/ Generics:\n\/\/ - reusable algorithms\n\/\/ - reusable containers\n\/\/ - compile-time type relationships\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">48. Real-World Use Case: Clock Interface for Testing<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\/\/ Clock describes the only time behavior\n\/\/ our service needs.\ntype Clock interface {\n\tNow() time.Time\n}\n\n\/\/ RealClock is used in production.\ntype RealClock struct{}\n\nfunc (RealClock) Now() time.Time {\n\treturn time.Now()\n}\n\n\/\/ FakeClock is useful in tests.\ntype FakeClock struct {\n\tCurrent time.Time\n}\n\nfunc (f FakeClock) Now() time.Time {\n\treturn f.Current\n}\n\ntype GreetingService struct {\n\tclock Clock\n}\n\nfunc (s GreetingService) Greeting() string {\n\thour := s.clock.Now().Hour()\n\n\tif hour &lt; 12 {\n\t\treturn \"Good morning\"\n\t}\n\n\treturn \"Good afternoon\"\n}\n\nfunc main() {\n\t\/\/ Test code can control time exactly.\n\tfake := FakeClock{\n\t\tCurrent: time.Date(\n\t\t\t2026,\n\t\t\ttime.August,\n\t\t\t17,\n\t\t\t9,\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\ttime.UTC,\n\t\t),\n\t}\n\n\tservice := GreetingService{\n\t\tclock: fake,\n\t}\n\n\tfmt.Println(service.Greeting())\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Good morning\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">49. Real-World Use Case: ID Generator<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ IDGenerator abstracts ID creation.\ntype IDGenerator interface {\n\tGenerate() string\n}\n\n\/\/ FixedIDGenerator is extremely useful in tests.\ntype FixedIDGenerator struct {\n\tID string\n}\n\nfunc (g FixedIDGenerator) Generate() string {\n\treturn g.ID\n}\n\ntype User struct {\n\tID   string\n\tName string\n}\n\ntype UserService struct {\n\tgenerator IDGenerator\n}\n\nfunc (s UserService) Create(name string) User {\n\treturn User{\n\t\t\/\/ Service does not know how IDs are generated.\n\t\tID: s.generator.Generate(),\n\n\t\tName: name,\n\t}\n}\n\nfunc main() {\n\tgenerator := FixedIDGenerator{\n\t\tID: \"test-123\",\n\t}\n\n\tservice := UserService{\n\t\tgenerator: generator,\n\t}\n\n\tuser := service.Create(\"Alice\")\n\n\tfmt.Println(user.ID)\n\tfmt.Println(user.Name)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ test-123\n\t\/\/ Alice\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">50. Real-World Use Case: Cache<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Cache describes the behavior\n\/\/ required by the service.\n\/\/\n\/\/ Production could use Redis.\n\/\/\n\/\/ Tests could use MemoryCache.\ntype Cache interface {\n\tGet(key string) (string, bool)\n\tSet(key string, value string)\n}\n\ntype MemoryCache struct {\n\tvalues map&#91;string]string\n}\n\nfunc NewMemoryCache() *MemoryCache {\n\treturn &amp;MemoryCache{\n\t\tvalues: make(map&#91;string]string),\n\t}\n}\n\nfunc (c *MemoryCache) Get(\n\tkey string,\n) (string, bool) {\n\tvalue, ok := c.values&#91;key]\n\n\treturn value, ok\n}\n\nfunc (c *MemoryCache) Set(\n\tkey string,\n\tvalue string,\n) {\n\tc.values&#91;key] = value\n}\n\nfunc main() {\n\tvar cache Cache = NewMemoryCache()\n\n\tcache.Set(\"language\", \"Go\")\n\n\tvalue, found := cache.Get(\"language\")\n\n\tfmt.Println(value)\n\tfmt.Println(found)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Go\n\t\/\/ true\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">51. Complete Mini Project: Order Processing<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Order is normal application data.\ntype Order struct {\n\tID     int\n\tEmail  string\n\tAmount float64\n}\n\n\/\/ OrderRepository describes persistence behavior.\ntype OrderRepository interface {\n\tSave(order Order) error\n}\n\n\/\/ PaymentProcessor describes payment behavior.\ntype PaymentProcessor interface {\n\tCharge(amount float64) error\n}\n\n\/\/ Notifier describes notification behavior.\ntype Notifier interface {\n\tNotify(\n\t\trecipient string,\n\t\tmessage string,\n\t) error\n}\n\n\/\/ OrderService depends only on interfaces.\n\/\/\n\/\/ It does NOT directly depend on:\n\/\/\n\/\/ PostgreSQL\n\/\/ Stripe\n\/\/ SMTP\n\/\/\n\/\/ This keeps business logic separate\n\/\/ from infrastructure details.\ntype OrderService struct {\n\trepository OrderRepository\n\tpayment    PaymentProcessor\n\tnotifier   Notifier\n}\n\n\/\/ Constructor injects dependencies.\nfunc NewOrderService(\n\trepository OrderRepository,\n\tpayment PaymentProcessor,\n\tnotifier Notifier,\n) *OrderService {\n\treturn &amp;OrderService{\n\t\trepository: repository,\n\t\tpayment:    payment,\n\t\tnotifier:   notifier,\n\t}\n}\n\n\/\/ Process contains business workflow.\nfunc (s *OrderService) Process(\n\torder Order,\n) error {\n\t\/\/ First charge payment.\n\tif err := s.payment.Charge(\n\t\torder.Amount,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Then save the order.\n\tif err := s.repository.Save(\n\t\torder,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Then notify the customer.\n\tif err := s.notifier.Notify(\n\t\torder.Email,\n\t\t\"Your order was processed\",\n\t); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ ------------------------------\n\/\/ Repository implementation\n\/\/ ------------------------------\n\ntype MemoryOrderRepository struct {\n\torders &#91;]Order\n}\n\nfunc (r *MemoryOrderRepository) Save(\n\torder Order,\n) error {\n\tr.orders = append(\n\t\tr.orders,\n\t\torder,\n\t)\n\n\tfmt.Println(\n\t\t\"Saved order:\",\n\t\torder.ID,\n\t)\n\n\treturn nil\n}\n\n\/\/ ------------------------------\n\/\/ Payment implementation\n\/\/ ------------------------------\n\ntype FakePaymentProcessor struct{}\n\nfunc (FakePaymentProcessor) Charge(\n\tamount float64,\n) error {\n\tfmt.Printf(\n\t\t\"Charged: $%.2f\\n\",\n\t\tamount,\n\t)\n\n\treturn nil\n}\n\n\/\/ ------------------------------\n\/\/ Notification implementation\n\/\/ ------------------------------\n\ntype ConsoleNotifier struct{}\n\nfunc (ConsoleNotifier) Notify(\n\trecipient string,\n\tmessage string,\n) error {\n\tfmt.Println(\n\t\t\"Notification to:\",\n\t\trecipient,\n\t)\n\n\tfmt.Println(\n\t\t\"Message:\",\n\t\tmessage,\n\t)\n\n\treturn nil\n}\n\nfunc main() {\n\t\/\/ Create concrete implementations.\n\trepository := &amp;MemoryOrderRepository{}\n\tpayment := FakePaymentProcessor{}\n\tnotifier := ConsoleNotifier{}\n\n\t\/\/ Inject them through interfaces.\n\tservice := NewOrderService(\n\t\trepository,\n\t\tpayment,\n\t\tnotifier,\n\t)\n\n\torder := Order{\n\t\tID:     1001,\n\t\tEmail:  \"alice@example.com\",\n\t\tAmount: 249.99,\n\t}\n\n\tif err := service.Process(order); err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ Charged: $249.99\n\t\/\/ Saved order: 1001\n\t\/\/ Notification to: alice@example.com\n\t\/\/ Message: Your order was processed\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">52. Testing the Order Service with Fakes<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\ntype Order struct {\n\tID     int\n\tEmail  string\n\tAmount float64\n}\n\ntype OrderRepository interface {\n\tSave(Order) error\n}\n\ntype PaymentProcessor interface {\n\tCharge(float64) error\n}\n\ntype Notifier interface {\n\tNotify(string, string) error\n}\n\ntype OrderService struct {\n\trepository OrderRepository\n\tpayment    PaymentProcessor\n\tnotifier   Notifier\n}\n\nfunc (s *OrderService) Process(\n\torder Order,\n) error {\n\tif err := s.payment.Charge(\n\t\torder.Amount,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.repository.Save(\n\t\torder,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.notifier.Notify(\n\t\torder.Email,\n\t\t\"processed\",\n\t)\n}\n\n\/\/ Fake repository records what was saved.\ntype FakeRepository struct {\n\tSavedOrder Order\n\tCalled     bool\n}\n\nfunc (f *FakeRepository) Save(\n\torder Order,\n) error {\n\tf.Called = true\n\tf.SavedOrder = order\n\n\treturn nil\n}\n\n\/\/ Fake payment records the charged amount.\ntype FakePayment struct {\n\tAmount float64\n\tCalled bool\n}\n\nfunc (f *FakePayment) Charge(\n\tamount float64,\n) error {\n\tf.Called = true\n\tf.Amount = amount\n\n\treturn nil\n}\n\n\/\/ Fake notifier records notification details.\ntype FakeNotifier struct {\n\tRecipient string\n\tMessage   string\n\tCalled    bool\n}\n\nfunc (f *FakeNotifier) Notify(\n\trecipient string,\n\tmessage string,\n) error {\n\tf.Called = true\n\tf.Recipient = recipient\n\tf.Message = message\n\n\treturn nil\n}\n\nfunc main() {\n\trepository := &amp;FakeRepository{}\n\tpayment := &amp;FakePayment{}\n\tnotifier := &amp;FakeNotifier{}\n\n\tservice := OrderService{\n\t\trepository: repository,\n\t\tpayment:    payment,\n\t\tnotifier:   notifier,\n\t}\n\n\torder := Order{\n\t\tID:     1,\n\t\tEmail:  \"alice@example.com\",\n\t\tAmount: 100,\n\t}\n\n\t_ = service.Process(order)\n\n\t\/\/ A real unit test would use testing.T,\n\t\/\/ but these prints show what can be verified.\n\n\tfmt.Println(payment.Called)\n\tfmt.Println(payment.Amount)\n\n\tfmt.Println(repository.Called)\n\tfmt.Println(repository.SavedOrder.ID)\n\n\tfmt.Println(notifier.Called)\n\tfmt.Println(notifier.Recipient)\n\n\t\/\/ Output:\n\t\/\/\n\t\/\/ true\n\t\/\/ 100\n\t\/\/ true\n\t\/\/ 1\n\t\/\/ true\n\t\/\/ alice@example.com\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">53. Common Mistake: Giant Interface<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Avoid creating an interface like this\n\/\/ unless a consumer truly requires ALL behavior.\n\/\/\n\/\/ type ApplicationManager interface {\n\/\/     Create()\n\/\/     Read()\n\/\/     Update()\n\/\/     Delete()\n\/\/     Import()\n\/\/     Export()\n\/\/     Backup()\n\/\/     Restore()\n\/\/     SendEmail()\n\/\/     GenerateReport()\n\/\/ }\n\n\/\/ Prefer small interfaces.\n\ntype Creator interface {\n\tCreate() error\n}\n\ntype Reader interface {\n\tRead() error\n}\n\ntype Updater interface {\n\tUpdate() error\n}\n\ntype Deleter interface {\n\tDelete() error\n}\n\n\/\/ Compose them only where necessary.\ntype CRUDService interface {\n\tCreator\n\tReader\n\tUpdater\n\tDeleter\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">54. Common Mistake: Interface for Every Struct<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype User struct {\n\tName string\n}\n\n\/\/ This method alone does NOT mean you need:\n\/\/\n\/\/ type UserInterface interface {\n\/\/     NameValue() string\n\/\/ }\n\/\/\n\/\/ If callers can simply use User,\n\/\/ use the concrete type.\n\/\/\n\/\/ Interfaces should represent useful abstraction,\n\/\/ not automatic wrappers around every struct.\n\nfunc (u User) NameValue() string {\n\treturn u.Name\n}\n\nfunc main() {\n\tuser := User{\n\t\tName: \"Alice\",\n\t}\n\n\t_ = user.NameValue()\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">55. Common Mistake: Overusing Type Switches<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ This kind of design:\n\/\/\n\/\/ switch value := thing.(type) {\n\/\/ case Dog:\n\/\/ case Cat:\n\/\/ case Person:\n\/\/ case Robot:\n\/\/ case Car:\n\/\/ }\n\/\/\n\/\/ may sometimes be necessary.\n\/\/\n\/\/ But if every type performs the same conceptual\n\/\/ behavior, an interface may be cleaner.\n\ntype Speaker interface {\n\tSpeak() string\n}\n\n\/\/ Now callers can simply:\n\/\/\n\/\/\tspeaker.Speak()\n\/\/\n\/\/ instead of repeatedly checking concrete types.\n\nfunc announce(s Speaker) string {\n\treturn s.Speak()\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">56. Common Mistake: Returning <code>any<\/code> Everywhere<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype User struct {\n\tID   int\n\tName string\n}\n\n\/\/ Poorly typed API:\n\/\/\n\/\/ func FindUser(id int) any\n\/\/\n\/\/ Caller would need to guess\/assert the result type.\n\n\/\/ Better API:\n\/\/\n\/\/ The return type clearly tells the caller\n\/\/ what to expect.\nfunc FindUser(id int) (User, error) {\n\treturn User{\n\t\tID:   id,\n\t\tName: \"Alice\",\n\t}, nil\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">57. Common Mistake: Wrong Receiver Type<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype Counter interface {\n\tIncrement()\n}\n\ntype NumberCounter struct {\n\tValue int\n}\n\n\/\/ Pointer receiver is required here\n\/\/ because Increment must change Value.\nfunc (c *NumberCounter) Increment() {\n\tc.Value++\n}\n\nfunc main() {\n\tcounter := NumberCounter{}\n\n\t\/\/ Direct call works because Go can take\n\t\/\/ the address of an addressable variable.\n\tcounter.Increment()\n\n\t\/\/ Interface assignment requires *NumberCounter.\n\tvar incrementer Counter = &amp;counter\n\n\tincrementer.Increment()\n\n\t\/\/ This would fail:\n\t\/\/\n\t\/\/ var wrong Counter = counter\n}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">58. Interface Design Decision Example<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\ntype User struct {\n\tID int\n}\n\n\/\/ Question:\n\/\/\n\/\/ \"Should I create an interface here?\"\n\/\/\n\/\/ Start by asking:\n\/\/\n\/\/ \"What does the CONSUMER actually need?\"\n\ntype UserFinder interface {\n\tFindByID(int) (User, error)\n}\n\n\/\/ This interface is useful when:\n\/\/\n\/\/ 1. Multiple implementations may exist.\n\/\/ 2. Tests need a fake implementation.\n\/\/ 3. The dependency crosses an architectural boundary.\n\/\/ 4. The consumer needs only this behavior.\n\/\/\n\/\/ An interface is probably unnecessary when:\n\/\/\n\/\/ 1. There is only a simple local concrete type.\n\/\/ 2. No substitution is needed.\n\/\/ 3. No testing boundary exists.\n\/\/ 4. The abstraction adds more complexity than value.\n\nfunc loadUser(\n\tfinder UserFinder,\n\tid int,\n) (User, error) {\n\treturn finder.FindByID(id)\n}\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">59. Final Interface Cheat Sheet<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ ------------------------------------\n\/\/ BASIC INTERFACE\n\/\/ ------------------------------------\n\ntype Speaker interface {\n\tSpeak() string\n}\n\n\/\/ ------------------------------------\n\/\/ IMPLEMENTATION\n\/\/ ------------------------------------\n\ntype Dog struct{}\n\nfunc (Dog) Speak() string {\n\treturn \"Woof\"\n}\n\n\/\/ Dog now implicitly satisfies Speaker.\n\n\/\/ ------------------------------------\n\/\/ MULTIPLE METHODS\n\/\/ ------------------------------------\n\ntype Service interface {\n\tStart() error\n\tStop() error\n}\n\n\/\/ ------------------------------------\n\/\/ INTERFACE COMPOSITION\n\/\/ ------------------------------------\n\ntype Reader interface {\n\tRead()\n}\n\ntype Writer interface {\n\tWrite()\n}\n\ntype ReadWriter interface {\n\tReader\n\tWriter\n}\n\n\/\/ ------------------------------------\n\/\/ ANY\n\/\/ ------------------------------------\n\n\/\/ any is equivalent to interface{}.\n\/\/\n\/\/ Use it when arbitrary values are genuinely needed.\n\nfunc printAnything(value any) {\n\t_ = value\n}\n\n\/\/ ------------------------------------\n\/\/ TYPE ASSERTION\n\/\/ ------------------------------------\n\nfunc assertion(value any) {\n\ttext, ok := value.(string)\n\n\tif ok {\n\t\t_ = text\n\t}\n}\n\n\/\/ ------------------------------------\n\/\/ TYPE SWITCH\n\/\/ ------------------------------------\n\nfunc typeSwitch(value any) {\n\tswitch v := value.(type) {\n\tcase string:\n\t\t_ = v\n\n\tcase int:\n\t\t_ = v\n\t}\n}\n\n\/\/ ------------------------------------\n\/\/ COMPILE-TIME CHECK\n\/\/ ------------------------------------\n\nvar _ Speaker = Dog{}\n\n\/\/ ------------------------------------\n\/\/ GENERIC CONSTRAINT\n\/\/ ------------------------------------\n\ntype Number interface {\n\t~int | ~float64\n}\n\nfunc Add&#91;T Number](a, b T) T {\n\treturn a + b\n}\n\n\/\/ ------------------------------------\n\/\/ MOST IMPORTANT RULE\n\/\/ ------------------------------------\n\/\/\n\/\/ A Go interface should answer:\n\/\/\n\/\/ \"What behavior does this consumer need?\"\n\/\/\n\/\/ not:\n\/\/\n\/\/ \"What interface can I create for this struct?\"\n\/\/\n\/\/ Good interfaces are usually:\n\/\/\n\/\/ - small\n\/\/ - behavior-focused\n\/\/ - consumer-focused\n\/\/ - easy to implement\n\/\/ - easy to test\n\/\/ - useful at dependency boundaries\n\nfunc main() {}\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">60. Final Mental Model<\/h1>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\n\/\/ Think about Go interfaces like this:\n\/\/\n\/\/                      Speaker\n\/\/                         |\n\/\/                  requires Speak()\n\/\/                         |\n\/\/             +-----------+-----------+\n\/\/             |           |           |\n\/\/            Dog        Person      Robot\n\/\/             |           |           |\n\/\/          Speak()     Speak()      Speak()\n\/\/\n\/\/ Speaker does not care:\n\/\/\n\/\/ \"What ARE you?\"\n\/\/\n\/\/ Speaker cares:\n\/\/\n\/\/ \"Can you Speak()?\"\n\/\/\n\/\/ That leads to the core Go interface idea:\n\/\/\n\/\/ ------------------------------------------------\n\/\/\n\/\/ INTERFACE = REQUIRED BEHAVIOR\n\/\/\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Struct:\n\/\/\n\/\/\ttype User struct {\n\/\/\t    Name string\n\/\/\t}\n\/\/\n\/\/ answers:\n\/\/\n\/\/ \"What data does this value contain?\"\n\/\/\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Interface:\n\/\/\n\/\/\ttype Saver interface {\n\/\/\t    Save() error\n\/\/\t}\n\/\/\n\/\/ answers:\n\/\/\n\/\/ \"What can this value do?\"\n\/\/\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Use interfaces especially for:\n\/\/\n\/\/ - databases\n\/\/ - repositories\n\/\/ - HTTP clients\n\/\/ - payment providers\n\/\/ - email systems\n\/\/ - notification services\n\/\/ - caches\n\/\/ - file systems\n\/\/ - clocks\n\/\/ - external APIs\n\/\/ - loggers\n\/\/ - queues\n\/\/ - testing dependencies\n\/\/\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Remember these rules:\n\/\/\n\/\/ 1. Interface implementation is implicit.\n\/\/\n\/\/ 2. Required method signatures must match.\n\/\/\n\/\/ 3. Keep interfaces small.\n\/\/\n\/\/ 4. Define interfaces around consumer needs.\n\/\/\n\/\/ 5. Pointer receivers affect interface satisfaction.\n\/\/\n\/\/ 6. any is interface{}.\n\/\/\n\/\/ 7. Use safe type assertions when type is uncertain.\n\/\/\n\/\/ 8. Type switches inspect dynamic types.\n\/\/\n\/\/ 9. A nil interface differs from an interface\n\/\/    containing a typed nil pointer.\n\/\/\n\/\/ 10. Interfaces and generics solve different problems.\n\/\/\n\/\/ 11. Generic constraints can also be interfaces.\n\/\/\n\/\/ 12. Do not create an interface for every struct.\n\/\/\n\/\/ 13. Use interfaces where abstraction gives real value.\n\/\/\n\/\/ 14. Prefer behavior-oriented designs.\n\/\/\n\/\/ 15. Ask:\n\/\/\n\/\/     \"What behavior does this code actually need?\"\n\/\/\n\/\/ That question is the foundation of good\n\/\/ interface design in Go.\n\nfunc main() {}\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>These three concepts are confusing initially because a method looks almost exactly like a function. The easiest way is to learn them in this order: Function \u2192&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1052","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/1052","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/comments?post=1052"}],"version-history":[{"count":6,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/1052\/revisions"}],"predecessor-version":[{"id":1105,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/1052\/revisions\/1105"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/media?parent=1052"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/categories?post=1052"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/tags?post=1052"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}