搜尋
首頁後端開發Golang映射中的多種函數類型,Golang

映射中的多種函數類型,Golang

映射是Golang中一種強大的資料結構,它允許我們將一個值與另一個值相關聯。在Golang中,我們可以使用映射來實作各種不同類型的函數。 php小編柚子將在本文中介紹映射中的多種函數類型,包括普通函數、匿名函數和方法。不僅如此,我們還將探討如何在映射中使用函數作為值,並展示它們的強大功能和靈活性。無論您是初學者還是有經驗的Golang開發者,本文都會為您提供有用的知識和實例來幫助您更好地理解和應用映射中的函數類型。讓我們開始探索吧!

問題內容

我希望將使用者輸入連接到函數。使用者輸入是字串。例如, "func_name=MyPrintf&s1=你好,世界\!" 或者 "func_name=MyAdd&i1=1&i2=2"

每個函數的程式碼是,

func MyPrintf(s1 string) {
    fmt.Println(s1)
}

func MyAdd(i1, i2 int) {
    fmt.Println(i1, i2)
}

我想要一張如下圖的地圖,

type Myfunc func(string) | func(int, int)   // <- Of course, it's wrong code, just I hope like this.

myMap := make(map[string]Myfunc)

myMap["MyPrintf"] = MyPrintf
myMap["MyAdd"] = MyAdd

myMap 可以透過使用者輸入的 func_name 字串呼叫函數。

myMap[func_name](s1) 輸出:你好,世界! myMap[func_name](i1, i2) 輸出:3

這可能嗎? 也許我認為使用“eval”是可能的,但我聽說使用“eval”不好。所以,我想到使用函數指針,但是Golang中沒有函數指針。

我嘗試了一些 Golang 通用編程,

type Myfunc interface {
    func(string) | func(int, int)
}

myMap := make(map[string]Myfunc)

輸出:發生錯誤:無法在類型限制之外使用類型 Myfunc:介麵包含類型約束

再嘗試,

myMap := make(map[string]interface{})

myMap["MyPrintf"] = interface{}(MyPrintf)
myMap["MyPrintf"].(func(string))("Hello, world!")

輸出:你好,世界!

myMap["MyAdd"] = interface{}(MyAdd)
myMap["MyAdd"].(func(int,int))(1, 2)

輸出:3

它可以工作,但必須指定正確的函數類型,這不太舒服。我認為這種方式不適合我的場景。請給我幫忙。 我為我糟糕的英語寫作感到抱歉。

解決方法

你可以試試看這個:

我必須說這不是一個好的做法,因為錯誤類型導致的恐慌\錯誤沒有得到驗證。我會考慮另一種方法。

package main

import "fmt"

type GeneralFunc func(args ...interface{})

func main() {
    // Create a map of functions with the type GeneralFunc
    functionsMap := map[string]GeneralFunc{
        "MyPrintf": func(args ...interface{}) { fmt.Println(args[0].(string)) },
        "MyAdd":    func(args ...interface{}) { fmt.Println(args[0].(int), args[1].(int)) },
    }

    // Use the functions from the map
    functionsMap["MyPrintf"]("Hello World")
    functionsMap["MyAdd"](2, 3)
}

以上是映射中的多種函數類型,Golang的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
測試代碼依賴於INET功能的代碼測試代碼依賴於INET功能的代碼May 03, 2025 am 12:20 AM

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

將GO的錯誤處理方法與其他語言進行比較將GO的錯誤處理方法與其他語言進行比較May 03, 2025 am 12:20 AM

go'serrorhandlingurturnserrorsasvalues,與Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

設計有效界面的最佳實踐設計有效界面的最佳實踐May 03, 2025 am 12:18 AM

AnefactiveInterfaceingoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForabStractionToswaPimplementations withoutchangingCallingCode.3)

集中式錯誤處理策略集中式錯誤處理策略May 03, 2025 am 12:17 AM

集中式錯誤處理在Go語言中可以提升代碼的可讀性和可維護性。其實現方式和優勢包括:1.將錯誤處理邏輯從業務邏輯中分離,簡化代碼。 2.通過集中處理錯誤,確保錯誤處理的一致性。 3.使用defer和recover來捕獲和處理panic,增強程序健壯性。

init in Init函數的替代方案,用於go中的包裝初始化init in Init函數的替代方案,用於go中的包裝初始化May 03, 2025 am 12:17 AM

Ingo,替代詞InivestoIniTfunctionsIncludeCustomInitializationfunctionsandsingletons.1)customInitializationfunctions hownerexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssetupssetupssetups.2)單次固定無元素限制ininconconcurrent

與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。