GO中接口的好处

GO中接口的好处



在GO中,接口不同于其他流行的编程语言,例如Java,C ++,PHP。它们具有一些设计优势。在本文中,我将尝试解释原因。

我将介绍这些好处,提供示例,并讨论使用接口时可能出现的一些问题。



GO中的接口有何特别之处?



. , python, js, ruby. , , . GO TypeScript. .

. , , , .

PHP:



class Human implements Walkable
{
}

class Mountain
{
    public function walkAround(Walkable $walkable) {...}
}


:



$human = new Human();
$mountain = new Mountain();
$mountain.walkAround($human);


GO . , . , .



?





. . . - , . . , .. .



- , . .



.

, . . , :



package auth

import (
   "gitlab.com/excercice_detection/backend"
)

type userRepository interface {
   FindUserByEmail(email string) (backend.User, error)
   AddUser(backend.User) (userID int, err error)
   AddToken(userID int, token string) error
   TokenExists(userID int, token string) bool
}

// Auth  
type Auth struct {
   repository userRepository
   logger     backend.Logger
}

// NewAuth   
func NewAuth(repository userRepository, logger backend.Logger) *Auth {
   return &Auth{repository, logger}
}

// Autentificate    
func (auth Auth) Autentificate(userID int, token string) bool {
   return auth.repository.TokenExists(userID, token)
}


, .



main :



package main

import (
   "gitlab.com/excercice_detection/backend/auth"
   "gitlab.com/excercice_detection/backend/mysql"
)

func main() {
    logger := newLogger()
    userRepository := mysql.NewUserRepository(logger)
    err := userRepository.Connect()
    authService := auth.NewAuth(userRepository, logger)
...


userRepository, , , mysql , . . . .



. , . . , .



, , .





, . , . , , .

, .

. .. . . . , , : , , .





. , . .



:



type userRepositoryMock struct {
   user         backend.User
   findUserErr  error
   addUserError error
   addUserID    int
   addTokenErr  error
   tokenExists  bool
}

func (repository userRepositoryMock) FindUserByEmail(email string) (backend.User, error) {
   return repository.user, repository.findUserErr
}

func (repository userRepositoryMock) AddUser(backend.User) (userID int, err error) {
   return repository.addUserID, repository.addUserError
}

func (repository userRepositoryMock) AddToken(userID int, token string) error {
   return repository.addTokenErr
}

func (repository userRepositoryMock) TokenExists(userID int, token string) bool {
   return repository.tokenExists
}


, , userRepositoryMock userRepositor, , .





, . , , .

. , , , , , .



, , ?



, , , . , GO , . IDE GoLand .



, , . , .



, , ?



. . IDE , , . IDE , .





GO . , — , . , . , .



GO, . . , . GO , , .




All Articles