Go 语言程序员的进化
package fac
func Factorial(n int) int {
res := 1
for i := 1; i <= n; i++ {
res *= i
}
return res
}
package fac
func Factorial(n int) int {
if n == 0 {
return 1
} else {
return Factorial(n - 1) * n
}
}
package fac
func Factorial(n interface{}) interface{} {
v, valid := n.(int)
if !valid {
return 0
}
res := 1
for i := 1; i <= v; i++ {
res *= i
}
return res
}
package fac
import "sync"
func Factorial(n int) int {
var (
left, right = 1, 1
wg sync.WaitGroup
)
wg.Add(2)
pivot := n / 2
go func() {
for i := 1; i < pivot; i++ {
left *= i
}
wg.Done()
}()
go func() {
for i := pivot; i <= n; i++ {
right *= i
}
wg.Done()
}()
wg.Wait()
return left * right
}
package fac
func Factorial(n int) <-chan int {
ch := make(chan int)
go func() {
prev := 1
for i := 1; i <= n; i++ {
v := prev * i
ch <- v
prev = v
}
close(ch)
}()
return ch
}
package fac
/**
* @see https://en.wikipedia.org/wiki/Factorial
*/
type IFactorial interface {
CalculateFactorial() int
}
// FactorialImpl implements IFactorial.
var _ IFactorial = (*FactorialImpl)(nil)
/**
* Used to find factorial of the n.
*/
type FactorialImpl struct {
/**
* The n.
*/
n int
}
/**
* Constructor of the FactorialImpl.
*
* @param n the n.
*/
func NewFactorial(n int) *FactorialImpl {
return &FactorialImpl{
n: n,
}
}
/**
* Gets the n to use in factorial function.
*
* @return int.
*/
func (this *FactorialImpl) GetN() int {
return this.n
}
/**
* Sets the n to use in factorial function.
*
* @param n the n.
* @return void.
*/
func (this *FactorialImpl) SetN(n int) {
this.n = n
}
/**
* Returns factorial of the n.
*
* @todo remove "if" statement. Maybe we should use a factory or somthing?
*
* @return int.
*/
func (this *FactorialImpl) CalculateFactorial() int {
if this.n == 0 {
return 1
}
n := this.n
this.n = this.n - 1
return this.CalculateFactorial() * n
}
package fac
// Factorial returns n!.
func Factorial(n int) int {
res := 1
for i := 1; i <= n; i++ {
res *= i
}
return res
}
package fac
// Factorial returns n!.
func Factorial(n int) int {
res := 1
for i := 1; i <= n; i++ {
res *= i
}
return res
}
本文文字及图片出自 The Evolution of a Go Programmer
你也许感兴趣的:
- Go语言有个“好爹”反而被程序员讨厌?
- 【外评】为什么人们对 Go 1.23 的迭代器设计感到愤怒?
- 【译文】Go语言性能从 1.0 版到 1.22 版
- 【译文】面试时,有人问我喜欢Go语言什么?
- 4 秒处理 10 亿行数据! Go 语言的 9 大代码方案,一个比一个快
- 【译文】Go语言设计:我们做对了什么,做错了什么
- 最好的 Go 框架就是不用框架?
- 吵翻了!到底该选 Rust 还是 Go,成 2023 年最大技术分歧
- “Go 语言的优点、缺点和平淡无奇之处”的十年
- 为什么不用Go开发操作系统?
你对本文的反应是: