TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Interface Example

Use an interface with a method. Implement the method and pass a struct as an interface.
Interface. An interface contains a method set. Every type that has an interface's methods automatically implements that interface.
With interfaces, we can unify code that uses diverse types. A func can act on the interface, not the many structs that might implement those methods.Built-Ins
An example. This program implements an interface. The "type Page" is an interface that requires one method: Print. And HtmlPage implements Page.

Note: An interface can be implemented by specifying all the required methods, or it can just use a name (like Page within HtmlPage here).

Main: This creates a new instance of the HtmlPage struct, which is a type that implements Page.

Display: This func receives any variable that implements Page. So we can just pass an HtmlPage to it.

Print: Finally the Print method is invoked through the Page interface. It uses the HtmlPage implementation.

Golang program that uses interface package main import "fmt" type Page interface { Print(value int) } type HtmlPage struct { // Implement the Page interface. Page } func (h *HtmlPage) Print(value int) { // Implement Print for HtmlPage struct. fmt.Printf("HTML %v", value) fmt.Println() } func display(p Page) { // Call Print from Page interface. // ... This uses the HtmlPage implementation. p.Print(5) } func main() { // Create an HtmlPage instance. p := new(HtmlPage) display(p) } Output HTML 5
Result. The above interface example program ends up invoking the Print() method. It prints HTML 5 because the int argument specified is 5.
An abstraction. Interfaces allow us to create an abstraction upon existing types. The Page abstraction above could be used on many different page structs, not just HtmlPage.
A summary. Interfaces in Go are powerful. With them we gain a way to write code that acts upon many structs at once. This unifies and improves programs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf