In Go, the two methods of function type conversion are type conversion and function adapter. The type conversion performs better at 400 nanoseconds, while the function adapter performs worse at 600 nanoseconds.
Function type conversion refers to converting one function type to another function type. In Go, you can use type conversion
or func adapter
for function type conversion.
package main import "fmt" func main() { // 定义一个返回字符串的函数 getString := func() string { return "Hello, World!" } // 将 getString 转换为返回 int 的函数 getInt := func() int { return len(getString()) } fmt.Println(getInt()) // 输出 13 }
package main import "fmt" type StringToInt func() int func getStringToIntAdapter(getString func() string) StringToInt { return func() int { return len(getString()) } } func main() { getString := func() string { return "Hello, World!" } getInt := getStringToIntAdapter(getString) fmt.Println(getInt()) // 输出 13 }
The following is a performance comparison of the two methods:
Method | Time (nanoseconds) |
---|---|
400 | |
600 |
map and
filter) to different type of data. For example:
// 将字符串列表转换为整数列表 func mapToInts(strs []string) []int { return map(func(s string) int { return len(s) }, strs) }
The above is the detailed content of Performance comparison of golang function type conversion. For more information, please follow other related articles on the PHP Chinese website!