> 백엔드 개발 > Golang > Small Go 인터페이스 예: 신분증 증명

Small Go 인터페이스 예: 신분증 증명

Patricia Arquette
풀어 주다: 2025-01-12 11:01:41
원래의
456명이 탐색했습니다.

Small Go interfaces example: proof of identity cards

이 튜토리얼에서는 초보자를 위한 Go 인터페이스를 보여줍니다. 신분증(ID 카드, 운전면허증, 여권)에 대한 방법을 정의하는 ProofOfId 인터페이스와 국가 나열을 위한 CountriesList 인터페이스를 만들어 보겠습니다. 이는 인터페이스가 다형성의 형태로 작동하여 다른 언어의 상속을 대체하는 방법을 보여줍니다.

프로젝트 설정

  1. 프로젝트 디렉토리 생성: mkdir proof-of-identity-checker && cd proof-of-identity-checker
  2. Go 모듈 초기화: go mod init <yourname>/proof-of-identity-checker(<yourname>를 자신의 이름이나 적절한 식별자로 바꾸세요).
  3. 코드 편집기에서 디렉터리를 엽니다.

인터페이스 정의(interfaces.go)

package main

import "time"

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

type CountriesList interface {
    getCountries() []string
}
로그인 후 복사

ProofOfId에는 getExpDate(), getName(), getObtentionDate()이 필요합니다. CountriesList에는 getCountries()이 필요합니다.

인터페이스 기반 기능(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)
    }
}
로그인 후 복사

신분증 유형 구현

  • 신분증(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-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.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
}
로그인 후 복사

테스트 중(main.go 계속)

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)
}
로그인 후 복사

go run .

으로 실행

결론

이 예는 Go 인터페이스가 객체 간 계약을 정의하고 코드 재사용성과 유지 관리성을 향상시켜 유연한 코드를 구현하는 방법을 보여줍니다. IdentityVerification 함수의 날짜 확인 로직

을 완성하려면 날짜 비교를 위해 제공된 링크를 참조해야 합니다.

위 내용은 Small Go 인터페이스 예: 신분증 증명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿