GO語言"reflect"包中"MakeFunc"函數的用法及代碼示例。
用法:
func MakeFunc(typ Type, fn func(args []Value)(results []Value)) Value
MakeFunc 返回一個包含函數 fn 的給定類型的新函數。調用時,該新函數執行以下操作:
- converts its arguments to a slice of Values. - runs results := fn(args). - returns the results as a slice of Values, one per formal result.
實現 fn 可以假設參數 Value 切片具有由 typ 給出的參數數量和類型。如果 typ 說明了一個可變參數函數,那麽最終的 Value 本身就是一個表示可變參數參數的切片,就像在可變參數函數的主體中一樣。 fn 返回的結果值切片必須具有 typ 給定的結果數量和類型。
Value.Call 方法允許調用者根據值調用類型化函數;相反,MakeFunc 允許調用者根據值實現類型化函數。
文檔的示例部分包含如何使用MakeFunc 為不同類型構建交換函數的說明。
例子:
package main
import (
"fmt"
"reflect"
)
func main() {
// swap is the implementation passed to MakeFunc.
// It must work in terms of reflect.Values so that it is possible
// to write code without knowing beforehand what the types
// will be.
swap := func(in []reflect.Value) []reflect.Value {
return []reflect.Value{in[1], in[0]}
}
// makeSwap expects fptr to be a pointer to a nil function.
// It sets that pointer to a new function created with MakeFunc.
// When the function is invoked, reflect turns the arguments
// into Values, calls swap, and then turns swap's result slice
// into the values returned by the new function.
makeSwap := func(fptr any) {
// fptr is a pointer to a function.
// Obtain the function value itself (likely nil) as a reflect.Value
// so that we can query its type and then set the value.
fn := reflect.ValueOf(fptr).Elem()
// Make a function of the right type.
v := reflect.MakeFunc(fn.Type(), swap)
// Assign it to the value fn represents.
fn.Set(v)
}
// Make and call a swap function for ints.
var intSwap func(int, int) (int, int)
makeSwap(&intSwap)
fmt.Println(intSwap(0, 1))
// Make and call a swap function for float64s.
var floatSwap func(float64, float64) (float64, float64)
makeSwap(&floatSwap)
fmt.Println(floatSwap(2.72, 3.14))
}
輸出:
1 0 3.14 2.72
相關用法
- GO MakeTable用法及代碼示例
- GO Map用法及代碼示例
- GO MarshalIndent用法及代碼示例
- GO Marshal用法及代碼示例
- GO MatchString用法及代碼示例
- GO Match用法及代碼示例
- GO MethodSet用法及代碼示例
- GO Mul32用法及代碼示例
- GO Mkdir用法及代碼示例
- GO MkdirTemp用法及代碼示例
- GO Modf用法及代碼示例
- GO Mul64用法及代碼示例
- GO Mod用法及代碼示例
- GO MultiReader用法及代碼示例
- GO MultiWriter用法及代碼示例
- GO Month用法及代碼示例
- GO MkdirAll用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 MakeFunc。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。