相关疑难解决方法(0)

如何在go中添加新方法到现有类型?

我想在gorilla/mux路由和路由器类型上添加一个方便的util方法:

package util

import(
    "net/http"
    "github.com/0xor1/gorillaseed/src/server/lib/mux"
)

func (r *mux.Route) Subroute(tpl string, h http.Handler) *mux.Route{
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

func (r *mux.Router) Subroute(tpl string, h http.Handler) *mux.Route{
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}
Run Code Online (Sandbox Code Playgroud)

但是编译器通知我

无法在非本地类型mux.Router上定义新方法

那我怎么做到这一点?我是否创建了一个具有匿名mux.Route和mux.Router字段的新结构类型?或者是其他东西?

extension-methods go

100
推荐指数
2
解决办法
5万
查看次数

如何在go中实现类似的界面?

我最近开始研究Go并面临下一期.我想实现Comparable接口.我有下一个代码:

type Comparable interface {
    compare(Comparable) int
}
type T struct {
    value int
}
func (item T) compare(other T) int {
    if item.value < other.value {
        return -1
    } else if item.value == other.value {
        return 0
    }
    return 1
}
func doComparison(c1, c2 Comparable) {
    fmt.Println(c1.compare(c2))
}
func main() {
    doComparison(T{1}, T{2})
}
Run Code Online (Sandbox Code Playgroud)

所以我收到了错误

cannot use T literal (type T) as type Comparable in argument to doComparison:
    T does not implement Comparable (wrong type for compare method)
        have …
Run Code Online (Sandbox Code Playgroud)

go go-interface

5
推荐指数
1
解决办法
1723
查看次数

我认为我误解了 Go 多态性/接口/结构

我不明白为什么下面的代码不能编译。

我很困惑为什么 Go 说HistoryReader没有正确实现IReaderHistoryBook实现IBook. 当尝试将 a 添加到 s 的切片时,为什么Read(book Ibook)和不能同时接受?Read(book HistoryBook)HistoryReaderIReader

package main

type IReader interface {
   Read(book IBook)
}

// HistoryReader implements IReader
type HistoryReader struct{}

func (r *HistoryReader) Read(book HistoryBook) {
   // ...
}

type IBook interface{}

// HistoryBook implements IBook
type HistoryBook struct{}

func main() {
   var readerSlice []IReader

   _ = append(readerSlice, &HistoryReader{})
}
Run Code Online (Sandbox Code Playgroud)
package main

type IReader interface {
   Read(book IBook)
}

// …
Run Code Online (Sandbox Code Playgroud)

polymorphism struct interface go

-1
推荐指数
1
解决办法
47
查看次数

Go type-error:struct没有实现接口

// BEGIN: external library

type realX struct {}

type realY struct {}

func (realX) Do() realY {
  return realY{}
}

// END

type A struct {
  a myX
}

type myY interface {}

type myX interface {
  Do() myY
}

func foo (arg1 myY) {
}

func main() {
    foo(realY{})
    x := A{realX{}}
    fmt.Println("Hello, playground")
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

cannot use realX literal (type realX) as type myX in field value:
    realX does not implement myX (wrong type for Do method)
        have …
Run Code Online (Sandbox Code Playgroud)

testing mocking go

-6
推荐指数
1
解决办法
454
查看次数