DEV Community

Shelner
Shelner

Posted on

Go basics

Package Declaration

package repositories 
Enter fullscreen mode Exit fullscreen mode
  • Declares that this file belongs to the repositories packages.
  • Go organize code by package.
  • main is the entry point package; other packages are for organization.

Import Statement

import "project/internal/models" 
Enter fullscreen mode Exit fullscreen mode
  • imports another package (models).
  • Paths are module-relative (based on the go.mod name).

Interface Declaration

type UserRepository interface { GetAllUsers() []models.User } 
Enter fullscreen mode Exit fullscreen mode
  • type <Name> interface {} defines an interface.
  • GetAllUsers() []models.User declares a method:
    • Returns a slice([]) of User structs from models.

Struct Definition

type userRepo struct{} 
Enter fullscreen mode Exit fullscreen mode
  • Defines a struct named userRepo with no fields.
  • Structs in Go are like classes or objects, but without methods inline.

Constructor Function

func NewUserRepository() UserRepository { return &userRepo{} } 
Enter fullscreen mode Exit fullscreen mode
  • func defines a function named NewUserRepository.
  • Returns a UserRepository interface.
  • &userRepo{} creates a pointer to a new userRepo struct.

Method Implementation

func (r *userRepo) GetAllUsers() []models.User { return []models.User{ {ID: 1}, {ID: 2} } } 
Enter fullscreen mode Exit fullscreen mode
  • This is a method on the struct userRepo.
  • (r *userRepo) declares a receiver (this in TS).
  • Returns a hardcoded slice of User objects.

Top comments (0)