使用回调函数将两个数字相加

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

Adding two numbers with callback funciton

问题

在Go语言中,可以使用函数闭包(function closure)来实现类似的功能。闭包是指一个函数可以访问并操作其外部作用域中的变量。下面是一个示例代码,展示了如何在Go中实现类似的加法操作:

package main

import "fmt"

func Add(a int) func(int) int {
	return func(b int) int {
		return a + b
	}
}

func main() {
	result := Add(5)(3)
	fmt.Println(result) // 输出 8
}

在上面的代码中,Add 函数返回一个闭包函数,该闭包函数接受一个整数参数 b,并返回 a + b 的结果。通过 Add(5)(3) 的调用方式,可以实现将两个数字相加的效果。

英文:

What is the idiomatic approach for adding two numbers in this kind of manner
Add(5)(3) -> This is done in C# with delegate but I'm not sure what the right way to do that in Go since there's no delegate.

答案1

得分: 0

返回一个函数,该函数从封闭作用域获取第一个值,并从参数中获取第二个数字。

func Add(a int) func(int) int {
	return func(b int) int {
		return a + b
	}
}

fmt.Println(Add(3)(5)) // 输出 8

这段代码并不符合惯用写法。惯用的写法是 3 + 5

英文:

Return a function that gets the first value from the the enclosing scope and the second number from an argument.

func Add(a int) func(int) int {
	return func(b int) int {
		return a + b
	}
}

fmt.Println(Add(3)(5)) // prints 8

None of this is idiomatic. The idiomatic code is 3 + 5.

答案2

得分: -1

在Go语言中,惯用的做法是不这样做。

Go语言强调性能和过程化的特性,这意味着函数式编程中的柯里化等模式在Go语言中是强烈反对的。在Go语言中,唯一惯用的两个数相加的方式是:

sum := 5 + 3

你可以通过返回一个函数的方式来实现柯里化:

func Add(val int) func(int) int {
    return func (other int) int {
        return val + other
    }
}

但你不应该这样做。这会增加复杂性,并且会减慢程序的运行速度,而没有任何好处。

英文:

The idiomatic way to do that in Go is not to do that.

Go's emphasis on performance and procedural nature means that functional patterns like currying are strongly anti-idiomatic. The only idiomatic way to add two numbers is Go is:

sum := 5 + 3

You could implement it with a function returning a function

func Add(val int) func(int) int {
    return func (other int) int {
        return val + other
    }
}

But you shouldn't. It adds complexity and slows down your program without any befit.

huangapple
  • 本文由 发表于 2022年5月18日 02:27:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/72279011.html
匿名

发表评论

匿名网友

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

确定