functiongopackagecrudgoland

Cannot access to a function from another package in GO


Hi I'm new and I'm learning GOlang using GO 1.20.7 and GOLand trying to write a simple crud application with Gorilla Mux and Gorm. Writing my controller (in controllers package) I'm not able to access the GetAllBooks func wrote into the models package. I thought it could be a problem of uppercase/lowercase but I think it is correct.

Here's my controller:

package controllers

import (
    "github.com/myname/go-bookstore/pkg/models"
    "net/http"
)

var NewBook model.Book

func GetBook(w http.ResponseWriter, r *http.Request) {
    newBooks := models.GetAllBooks()
}

And here my models package from where the func is called:

package models

import (
    "github.com/myname/go-bookstore/pkg/config"
    "github.com/jinzhu/gorm"
)

var db *gorm.DB

type Book struct {
    gorm.Model
    Name        string `gorm:"" json:"name"`
    Author      string `json:"author"`
    Publication string `json:"publication"`
}

func init() {
    config.Connect()
    db = config.GetDB()
    db.AutoMigrate(&Book{})
}

func (b *Book) CreateBook() *Book {
    db.NewRecord(b)
    db.Create(&b)
    return (b)
}

func (b *Book) GetAllBooks() []Book {
    var Books []Book
    db.Find(&Books)
    return Books
}

My IDE on the GetAllBook method call in controllers says "Unresolved reference 'GetAllBooks'".


Solution

  • As @mkorpriva said in the comments, GetAllBooks is a method, not a function! Just Change GetAllBooks method to a function like this:

    func GetAllBooks() []Book {
        var Books []Book
        db.Find(&Books)
        return Books
    }
    

    as documentation says,

    Go does not have classes. However, you can define methods on types.

    you may see an online tutorial to completely understand methods and their use cases. good luck.