我有一个映射,其中一个结构作为键,一个函数作为值,我想在检索给定键的值时调用函数
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)我得到了内存地址,我该如何在该地址调用函数?
我试过 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("%s\n", 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 := "\r\n"
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("%s\n", 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"]()
关于go - 在内存地址调用 func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351857/
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时
如何找到调用此方法的位置?defto_xml(options={})binding.pryoptions=options.to_hifoptions&&options.respond_to?(:to_h)serializable_hash(options).to_xml(options)end 最佳答案 键入caller。这将返回当前调用堆栈。文档:Kernel#caller.例子[0]%rspecspec10/16|===================================================62=====
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"