gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:41:08 26 4
gpt4 key购买 nike

我正在用 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 {
BaseRoute
URI string
}

// myEndpoint is an example endpoint implementation
// which only implements a GET request.
type myEndpoint Endpoint

func (myEndpoint) Get() string {
return "myEndpoint get"
}

func main() {
myEndpointInstance := myEndpoint{URI: "/myEndpoint"}
fmt.Println(myEndpointInstance.URI)
fmt.Println(myEndpointInstance.Get())
fmt.Println(myEndpointInstance.Post())
}

此代码段将打印出以下内容:

/myEndpoint
myEndpoint get
base post

所以我对函数的覆盖按预期工作。现在我想知道在我的 main 函数中,在我声明 myEndpointInstance 之后,我能否以某种方式告诉我 Post 函数没有被覆盖并且仍然由底层 BaseRoute 实现而不实际调用该函数?理想情况下,我想要这样的东西:

func main() {
myEndpointInstance := myEndpoint{URI: "/myEndpoint"}
if myEndpointInstace.Post != BaseRoute.Post {
// do something
}
}

我试了一下 reflect 包,但没有发现任何有用的东西。

最佳答案

正如其他人所指出的,调用哪个方法是编译时决定的。因此您可以在编译时检查它,大多数 IDE 会将您导航到绑定(bind)到实际调用的方法。

如果你想在运行时检查这个,你可以比较函数指针。您不能比较函数值,它们是不可比较的(仅与 nil 值)。 Spec: Comparison operators :

Slice, map, and function values are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil.

这是你可以做到的:

myEndpointInstance := myEndpoint{URI: "/myEndpoint"}

v1 := reflect.ValueOf(myEndpointInstance.Post).Pointer()
v2 := reflect.ValueOf(myEndpointInstance.BaseRoute.Post).Pointer()
fmt.Println(v1, v2, v1 == v2)

v1 = reflect.ValueOf(myEndpointInstance.Get).Pointer()
v2 = reflect.ValueOf(myEndpointInstance.BaseRoute.Get).Pointer()
fmt.Println(v1, v2, v1 == v2)

这将输出(在 Go Playground 上尝试):

882848 882848 true
882880 882912 false

输出告诉 Post() 没有被“覆盖”(myEndpointInstance.PostmyEndpointInstance.BaseRoute.Post 相同),而Get() 是(myEndpointInstance.GetmyEndpointInstance.BaseRoute.Get 不同)。

查看相关问题:

How to compare 2 functions in Go?

Collection of Unique Functions in Go

关于function - 如何在不调用函数的情况下判断类型的基函数是否已在 Go 中被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com