Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type has no field or method

Tags:

methods

go

I have a problem with a struct's method. In one file (same package) I a struct:

type Task struct {
    ID       int    `json:"id"`
    Priority string `json:"priority"`
    Content  string `json:"content"`
}

The Task comes as a body in POST. Parsing the JSON to this struct works well. In other file I have a method:

func (task *Task) createTask() (err error) {
    data, err := bson.Marshal(&task)
    if err != nil {
        return errors.New("error in parsing incoming task")
    }
    rslt, err := collection.InsertOne(context.Background(), data)
    if err != nil {
        return errors.New("error in saving task to database")
    }
    fmt.Println(rslt.InsertedID)
    return nil
}

The Task structure is in the same file with my server. createTask() method is in the file which handles communication to mongoDB. When I run my server I have this error:

./server.go:53:12: task.createTask undefined (type Task has no field or method createTask)

Here is how I am calling the method:

var task Task
json.Unmarshal(body, &task)
err = task.createTask()

Do you have any ideas what am I doing wrong?

like image 379
mgalazka Avatar asked Jun 18 '26 00:06

mgalazka


1 Answers

This got me as well >.<

Go only considers functions that begin with a capital letter to be exported; including member functions. So you need to change:

func (task *Task) createTask() (err error) {
   ...

to

func (task *Task) CreateTask() (err error) {
   ...

and similarly at the call site.

Go's error unfortunately doesn't tell you how to fix this if you wrote the module and intend for the function to be exported.

like image 95
acenturyandabit Avatar answered Jun 20 '26 11:06

acenturyandabit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!