Go 程式設計師的演變,最後的「Rob Pike」這個梗看懂了嗎?

2020-02-18     Go語言中文網



通過一個階乘函數的不同寫法將 Go 程式設計師進行劃分。

初級 Go 程式設計師

package facfunc Factorial(n int) int {res := 1for i := 1; i <= n; i++ {res *= i}return res}

函數式 Go 程式設計師

package facfunc Factorial(n int) int {if n == 0 {return 1} else {return Factorial(n - 1) * n}}

泛型 Go 程式設計師

package facfunc Factorial(n interface{}) interface{} {v, valid := n.(int)if !valid {return 0}res := 1for i := 1; i <= v; i++ {res *= i}return res}

多線程優化的 Go 程式設計師

package facimport "sync"func Factorial(n int) int {var (left, right = 1, 1wg sync.WaitGroup)wg.Add(2)pivot := n / 2go 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}

發現型 Go 模式

package facfunc Factorial(n int) <-chan int {ch := make(chan int)go func() {prev := 1for i := 1; i <= n; i++ {v := prev * ich <- vprev = v}close(ch)}()return ch}

使用成熟的解決方案修復 Go 缺陷

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.nthis.n = this.n - 1return this.CalculateFactorial() * n}

高級 Go 程式設計師

package fac// Factorial returns n!.func Factorial(n int) int {res := 1for i := 1; i <= n; i++ {res *= i}return res}

Rob Pike(代碼全是黑白,頭條體現不出來)

package fac// Factorial returns n!.func Factorial(n int) int {res := 1for i := 1; i <= n; i++ {res *= i}return res}

來自:https://github.com/SuperPaintman/the-evolution-of-a-go-programmer ,啟發自《程式設計師的演變》https://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html

文章來源: https://twgreatdaily.com/zh-tw/l6k1dXABjYh_GJGVYZz-.html