Lloyd Moore
Lloyd Moore

Reputation: 3197

Method declarations with receivers in Go

The following errors:

./main.go:13: c.Set undefined (type redis.Conn has no field or method Set)
./main.go:19: invalid receiver type *redis.Conn (redis.Conn is an interface type)
./main.go:20: red.Send undefined (type *redis.Conn has no field or method Send)

are produced from this code:

package main

import (
    "encoding/json"
    "github.com/garyburd/redigo/redis"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    )

func setHandler(res http.ResponseWriter, req *http.Request) {
    c := connectRedis()
    c.Set("foo", "bar")
    data, _ := json.Marshal("{'order':1, 'weight': 100, 'reps': 5, 'rest': 1}")
    res.Header().Set("Content-Type", "application/json; charset=utf-8")
    res.Write(data)
}

func (red *redis.Conn) Set(key string, value string) error {
    if _, err := red.Send("set", key, value); err != nil {
        return err
    }
}

func connectRedis() redis.Conn {
    c, err := redis.Dial("tcp", ":6379")
    if err != nil {
            // handle error
    }
    defer c.Close()
    return c
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/sets.json", setHandler)
    http.Handle("/", r)
    err := http.ListenAndServe(":7000", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

How can I register a method when I have an interface?

Upvotes: 1

Views: 1229

Answers (2)

Mihai Stancu
Mihai Stancu

Reputation: 16107

You are trying to add a new method to a preexisting structure from another package; you cannot do that.

The right way to do it would be to define a structure in your own package which would alias the preexisting structure and inherit all of its methods. After doing that you will be able to add your new method to your new structure.

After that you can use your own structure everywhere instead so you can access the extra methods.

Upvotes: 3

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657138

You might be tempted now to see if you can attach methods and behavior to any type, say like an int or time.Time - not possible. You will be able to add methods for a type only if the type is defined in the same package.

from GoLang Tutorials - Methods on structs

Upvotes: 1

Related Questions