在内存地址调用函数



>我有一个映射,其中结构作为键,一个func作为值,我想在检索给定键的值时调用func

map[struct]func
map[
    {contact %!s(int=1)}:%!s(main.Controller=0x4c7b50) 
    {services/basket %!s(int=2)}:%!s(main.Controller=0x4c7ad0) 
    {categories %!s(int=1)}:%!s(main.Controller=0x4c7ae0) 
    {categories/{category} %!s(int=2)}:%!s(main.Controller=0x4c7af0)
    {categories/{category}/{product} %!s(int=3)}:%!s(main.Controller=0x4c7b00) 
    {basket %!s(int=1)}:%!s(main.Controller=0x4c7b10) 
    {checkout %!s(int=1)}:%!s(main.Controller=0x4c7b40) 
    {sitemap %!s(int=1)}:%!s(main.Controller=0x4c7b30) 
    {services/order %!s(int=2)}:%!s(main.Controller=0x4c7ac0) 
    {services/image %!s(int=2)}:%!s(main.Controller=0x4c7b20) 
    {/ %!s(int=1)}:%!s(main.Controller=0x4c7a00)
]
c := RouteMap[struct]

如果我fmt.Printf("%s", c)获取内存地址,如何在地址处调用 func?

我已经尝试过c((,但这给出了运行时错误:

%s
0x4c7b10%s
<nil>panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4c76f4]
goroutine 5 [running]:
main.RequestHandler(0x577ce0, 0xc042004018)
        C:/Users/mon/Desktop/server.go:91 +0x684
created by main.main
        C:/Users/mon/Desktop/server.go:41 +0x2a0

package main
import (
    "bufio"
    "bytes"
    "fmt"
    "net"
    "strings"
    "time"
)
var RouteMap = make(map[PathIdentifier]Controller)
func main() {
    ln, err := net.Listen("tcp", ":8080")
    if err != nil {
        // handle error
    }
    MapRoute("/", HomeController)
    MapRoute("categories", CategoriesController)
    MapRoute("categories/{category}", CategoryController)
    MapRoute("categories/{category}/{product}", CategoryProductController)
    MapRoute("basket", BasketController)
    MapRoute("checkout", CheckoutController)
    MapRoute("sitemap", SitemapController)
    MapRoute("contact", ContactController)
    MapRoute("services/order", OrderServiceController)
    MapRoute("services/basket", BasketServiceController)
    MapRoute("services/image", ImageServiceController)
    fmt.Printf("%sn", RouteMap)
    for {
        conn, err := ln.Accept()
        if err != nil {
            // handle error
        }
        go RequestHandler(conn)
    }
}
// ----------------------- Request & Response ---------------------------
func ParseQueryString() {}
func ParsePostData() {}
func ResponseHeaders() {}
func ParseRequestHeaders() {}
func RequestHandler(conn net.Conn) {
CrLf := "rn"
Terminator := CrLf + CrLf
defer func() {
    //fmt.Println("Closing connection...")
    conn.Close()
}()
timeoutDuration := 10 * time.Second
bufReader := bufio.NewReader(conn)
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
requestBytes, err := bufReader.ReadBytes('n')
if err != nil {
    fmt.Println(err)
    return
}
requestTokens := bytes.Split(requestBytes, []byte(" "))
requestMethod := string(requestTokens[0])
requestPath := string(requestTokens[1])
//requestHTTPVersion := string(requestTokens[2])
if requestMethod == "GET" {
    // Parse path
    pathTokens := strings.Split(requestPath, "/")
    segments := len(pathTokens)
    key := PathIdentifier{path: "categories/{category}/{product}", segments: (segments - 1)}
    c := RouteMap[key]
    fmt.Print("%sn", c)
}
    document := []byte("HTTP/1.1 200 OK" + CrLf + "Date: Mon, 27 Jul 2009 12:28:53 GMT" + CrLf + "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT" + CrLf + "Content-Length: 49" + CrLf + "Content-Type: text/html" + CrLf + "Connection: Closed" + Terminator + "<html><body><h1>Hello, World!</h1></body></html>" + Terminator)
    conn.Write(document)
}
// ----------------------------- Controller -----------------------------
type Controller func()
type PathIdentifier struct {
    path     string
    segments int
}
func MapRoute(view string, controller Controller) {
    if controller != nil {
        if view != "/" {
            pathTokens := strings.Split(view, "/")
            key := PathIdentifier{path: view, segments: len(pathTokens)}
            RouteMap[key] = controller
            return
        }
        key := PathIdentifier{path: view, segments: 1}
        RouteMap[key] = controller
    }
}
func HomeController() {
    fmt.Print("Invoking the HomeController.n")
}
func OrderServiceController() {
}
func BasketServiceController() {
}
func CategoriesController() {
}
func CategoryController() {
}
func CategoryProductsController() {
}
func CategoryProductController() {
}
func BasketController() {
}
func ImageServiceController() {
}
func SitemapController() {
}
func CheckoutController() {
}
func ContactController() {
}

我不确定您是否需要将其称为"按地址"。当您通过将其作为变量传递来调用时,编译器会在"后台"为您执行此操作。获取其地址并调用它。

如果您希望某种程度的间接性,则可以进行:

M := map[string]func()
M["function 1"] = F
// and then call them from map like 
M["function 1"]()

最新更新