Injecting an object in each function in Go My current project uses a database represented as object. Furthermore I want to implement methods like CreateUser(), DeleteUser() etc, but my current code requires the injection of the db-object as parameter in each function.

Making the db-object global would solve the problem, but I learnt that global variables are mostly seen as a bad practice. Are there any other solutions?

package main

import (
    "fmt"
    "time"

    "github.com/jinzhu/gorm"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
)

type User struct {
    ID        int
    Name      string `sql:"size:50"`
    Username  string `sql:"size:50"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

func CreateUser(db gorm.DB, name, username string) {
    user := User{
        Name:     name,
        Username: username,
    }

    db.Create(&amp;user)
}

func main() {
    db, err := gorm.Open("sqlite3", "data.sqlite3")

    if err != nil {
        fmt.Println(err)
    }

    db.DB()
    fmt.Println("Programm is running...")

    CreateUser(db, "John Doe", "johndoe")
}
Usually, when you have a lot of functions operating on the same data, it's worth considering making those functions methods on this data:

type UserDB struct {
    *gorm.DB
}

func (udb *UserDB) Create(name, username string) error {
    user := User{
        Name:     name,
        Username: username,
    }

    return udb.Create(&amp;user).Error
}

// etc.