Golang:确定函数的元数的函数?

huangapple go评论69阅读模式
英文:

Golang: Function to determine the arity of functions?

问题

可以编写一个函数来确定任意函数的元数(arity),例如:

func mult_by_2(x int) int {
    return 2 * x
}
fmt.Println(arity(mult_by_2)) // 输出 1
func add(x int, y int) int {
    return x + y
}
fmt.Println(arity(add)) // 输出 2
func add_3_ints(a, b, c int) int {
    return b + a + c
}
fmt.Println(arity(add_3_ints)) // 输出 3

请注意,arity 函数需要根据函数的参数列表来确定元数。你可以通过检查函数类型的参数数量来实现这一点。

英文:

Is it possible to write a function to determine the arity of arbitrary functions, such that:

1.

func mult_by_2(x int) int {
	  return 2 * x
}
fmt.Println(arity(mult_by_2)) //Prints 1

2.

func add(x int, y int) int {
	  return x + y
}
fmt.Println(arity(add)) //Prints 2

3.

func add_3_ints(a, b, c int) int {
	  return b + a + c
}
fmt.Println(arity(add_3_ints)) //Prints 3

答案1

得分: 5

你可以使用reflect包来编写这样一个函数:

import (
    "reflect"
)

func arity(value interface{}) int {
    ref := reflect.ValueOf(value)
    tpye := ref.Type()
    if tpye.Kind() != reflect.Func {
        // 在这里你可以定义自己的逻辑
        panic("value不是一个函数")
    }
    return tpye.NumIn()
}
英文:

You can write such a function using the reflect package:

import (
    "reflect"
)

func arity(value interface{}) int {
	ref := reflect.ValueOf(value)
	tpye := ref.Type()
	if tpye.Kind() != reflect.Func {
        // You could define your own logic here
		panic("value is not a function")
	}
	return tpye.NumIn()
}

huangapple
  • 本文由 发表于 2016年2月6日 22:55:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/35242401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定