search
HomeBackend DevelopmentGolangSmall Go interfaces example: proof of identity cards

Small Go interfaces example: proof of identity cards

This tutorial demonstrates Go interfaces for beginners. We'll create a ProofOfId interface defining methods for identity documents (ID card, driver's license, passport) and a CountriesList interface for listing countries. This illustrates how interfaces function as a form of polymorphism, replacing inheritance in other languages.

Project Setup

  1. Create a project directory: mkdir proof-of-identity-checker && cd proof-of-identity-checker
  2. Initialize a Go module: go mod init <yourname>/proof-of-identity-checker</yourname> (replace <yourname></yourname> with your name or a suitable identifier).
  3. Open the directory in your code editor.

Defining Interfaces (interfaces.go)

package main

import "time"

type ProofOfId interface {
    getExpDate() time.Time
    getName() string
    getObtentionDate() time.Time
}

type CountriesList interface {
    getCountries() []string
}

ProofOfId requires getExpDate(), getName(), and getObtentionDate(). CountriesList requires getCountries().

Interface-Based Functions (main.go)

package main

import "time"

// IdentityVerification checks if a proof of ID is valid (date-based).
func IdentityVerification(proof ProofOfId) bool {
    // ... (Date comparison logic would go here.  See the provided link for details.)
    return proof.getExpDate().After(time.Now()) //Example: Check if expiration date is in the future.
}

// DisplayVisitedCountries prints a list of visited countries.
func DisplayVisitedCountries(passport CountriesList) {
    countries := passport.getCountries()
    println("Visited countries:")
    for _, country := range countries {
        println(country)
    }
}

Implementing Identity Document Types

  • Identification Card (idcard.go)
package main

import "time"

type IdCard struct {
    Name          string
    ObtentionDate time.Time
    ExpDate       time.Time
}

func (card IdCard) getName() string {
    return card.Name
}

func (card IdCard) getExpDate() time.Time {
    return card.ExpDate
}

func (card IdCard) getObtentionDate() time.Time {
    return card.ObtentionDate
}
  • Driver's License (driver-license.go)
package main

import "time"

type DriverLicense struct {
    Name          string
    ObtentionDate time.Time
    ExpDate       time.Time
    Enterprise    string
}

func (license DriverLicense) getName() string {
    return license.Name
}

func (license DriverLicense) getExpDate() time.Time {
    return license.ExpDate
}

func (license DriverLicense) getObtentionDate() time.Time {
    return license.ObtentionDate
}

func (license DriverLicense) getEnterprise() string {
    return license.Enterprise
}
  • Passport (passport.go)
package main

import "time"

type Passport struct {
    Name             string
    ObtentionDate    time.Time
    ExpDate          time.Time
    VisitedCountries []string
}

func (passport Passport) getName() string {
    return passport.Name
}

func (passport Passport) getExpDate() time.Time {
    return passport.ExpDate
}

func (passport Passport) getObtentionDate() time.Time {
    return passport.ObtentionDate
}

func (passport Passport) getCountries() []string {
    return passport.VisitedCountries
}

Testing (main.go continued)

func main() {
    idCard := IdCard{ObtentionDate: time.Now().Add(24 * time.Hour), ExpDate: time.Now().Add(730 * 24 * time.Hour)}
    driverLicense := DriverLicense{ObtentionDate: time.Now().Add(-24 * time.Hour), ExpDate: time.Now().Add(365 * 24 * time.Hour)}
    passport := Passport{ObtentionDate: time.Now().Add(-24 * time.Hour), ExpDate: time.Now().Add(-1 * time.Hour), VisitedCountries: []string{"France", "Spain", "Belgium"}}

    println(IdentityVerification(idCard))
    println(IdentityVerification(driverLicense))
    println(IdentityVerification(passport))

    DisplayVisitedCountries(passport)
}

Run with go run .

Conclusion

This example shows how Go interfaces enable flexible code by defining contracts between objects, promoting code reusability and maintainability. The provided link for date comparison should be consulted to complete the IdentityVerification function's date checking logic.

The above is the detailed content of Small Go interfaces example: proof of identity cards. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

Go in Production: Real-World Use Cases and ExamplesGo in Production: Real-World Use Cases and ExamplesApr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

Custom Error Types in Go: Providing Detailed Error InformationCustom Error Types in Go: Providing Detailed Error InformationApr 26, 2025 am 12:09 AM

We need to customize the error type because the standard error interface provides limited information, and custom types can add more context and structured information. 1) Custom error types can contain error codes, locations, context data, etc., 2) Improve debugging efficiency and user experience, 3) But attention should be paid to its complexity and maintenance costs.

Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools