Method declarations with receivers in Go

huangapple go评论84阅读模式
英文:

Method declarations with receivers in Go

问题

以下是翻译好的内容:

以下是产生这些错误的代码:

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 {
        // 处理错误
    }
    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)
    }
}

当我有一个接口时,我如何注册一个方法?

英文:

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?

答案1

得分: 3

你正在尝试向来自另一个包的现有结构添加一个新方法,这是不允许的。

正确的做法是在你自己的包中定义一个结构,该结构将别名为现有结构并继承其所有方法。在这样做之后,你就可以向你的新结构中添加新方法。

之后,你可以在任何地方使用你自己的结构,以便访问额外的方法。

英文:

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.

答案2

得分: 1

你可能会想尝试将方法和行为附加到任何类型,比如int或time.Time,但这是不可能的。只有当类型在同一个包中定义时,你才能为该类型添加方法。

来自GoLang教程-结构体上的方法

英文:

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

huangapple
  • 本文由 发表于 2013年12月20日 19:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/20702321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定