相关疑难解决方法(0)

如何在最新的Go Week中比较指针相等的两个函数?

在Go中,有没有办法比较两个非零函数指针来测试相等性?我的平等标准是指针平等.如果没有,是否有任何特殊原因不允许指针相等?

截至目前,如果我试图以直截了当的方式做到这一点:

package main

import "fmt"

func SomeFun() {
}

func main() {
    fmt.Println(SomeFun == SomeFun)
}
Run Code Online (Sandbox Code Playgroud)

我明白了

./func-pointers.go:12: invalid operation: SomeFun == SomeFun (func can only be compared to nil)
Run Code Online (Sandbox Code Playgroud)

我的理解是这种行为最近被引入.


我用反射包找到了答案; 但Atom在下面建议这实际上会产生不确定的行为.有关更多信息和可能的替代解决方案,请参阅Atom的帖子.

package main

import "fmt"
import "reflect"

func SomeFun() { }

func AnotherFun() { }

func main() {
    sf1 := reflect.ValueOf(SomeFun)
    sf2 := reflect.ValueOf(SomeFun)
    fmt.Println(sf1.Pointer() == sf2.Pointer())

    af1 := reflect.ValueOf(AnotherFun)
    fmt.Println(sf1.Pointer() == af1.Pointer())
}
Run Code Online (Sandbox Code Playgroud)

输出:

true
false
Run Code Online (Sandbox Code Playgroud)

function-pointers go go-reflect

26
推荐指数
2
解决办法
1万
查看次数

如何比较Go中的2个函数?

例如,我有我要比较的函数列表:

http://play.golang.org/p/_rCys6rynf

type Action func(foo string)

type Handler struct {
  Get Action
  Post Action
}

var routes map[string]Handler

func Undefined(foo string) {
}

func Defined(foo string) {
}

func init() {
  routes = map[string]Handler{
    `/`: Handler{Defined,Undefined},
  }
}

func main() {
  for _, handler := range routes {
    if handler.Post != Undefined { 
      // do something
    } // invalid operation: (func(string))(handler.Post) != Undefined (func can only be compared to nil)


    if &handler.Post != &Undefined { 
      // do something 
    } // …
Run Code Online (Sandbox Code Playgroud)

function-pointers function go

4
推荐指数
2
解决办法
2878
查看次数

在不调用函数的情况下,如何判断类型的基本函数是否已在Go中被覆盖?

我正在Go中实现一个简单的路由器。当没有为该终结点实现调用的方法时,我曾经为每个终结点返回一个错误而使用大量冗余代码。我重构并制作了一个“基本”类型,该类型为每种请求类型提供了默认功能,这些功能仅返回未实现的错误。现在,我要做的就是为我要实现的给定端点重写特定的方法功能。在给定端点变量的情况下,直到我想弄清楚哪些方法已被覆盖,这一切都是有趣的游戏。

省略无关的细节,这是我现在想到的一个简单示例:

package main

import (
    "fmt"
)

// Route defines the HTTP method handlers.
type Route interface {
    Get() string
    Post() string
}

// BaseRoute is the "fallback" handlers,
// if those handlers aren't defined later.
type BaseRoute struct{}

func (BaseRoute) Get() string {
    return "base get"
}

func (BaseRoute) Post() string {
    return "base post"
}

// Endpoint holds a route for handling the HTTP request,
// and some other metadata related to that request.
type Endpoint struct …
Run Code Online (Sandbox Code Playgroud)

methods overriding function go

4
推荐指数
1
解决办法
91
查看次数