Go: Difference between revisions
Jump to navigation
Jump to search
(Created page with "http://golang.org/ ''Go is an open source programming language that makes it easy to build simple, reliable, and efficient software. '' Example: <pre> package main import "...") |
No edit summary |
||
| Line 23: | Line 23: | ||
// Function calls are evaluated left-to-right. |
// Function calls are evaluated left-to-right. |
||
fmt.Println(f(), f(), f(), f(), f()) |
fmt.Println(f(), f(), f(), f(), f()) |
||
} |
|||
</pre> |
|||
<pre> |
|||
// Concurrent computation of pi. |
|||
// See http://goo.gl/ZuTZM. |
|||
// |
|||
// This demonstrates Go's ability to handle |
|||
// large numbers of concurrent processes. |
|||
// It is an unreasonable way to calculate pi. |
|||
package main |
|||
import ( |
|||
"fmt" |
|||
"math" |
|||
) |
|||
func main() { |
|||
fmt.Println(pi(5000)) |
|||
} |
|||
// pi launches n goroutines to compute an |
|||
// approximation of pi. |
|||
func pi(n int) float64 { |
|||
ch := make(chan float64) |
|||
for k := 0; k <= n; k++ { |
|||
go term(ch, float64(k)) |
|||
} |
|||
f := 0.0 |
|||
for k := 0; k <= n; k++ { |
|||
f += <-ch |
|||
} |
|||
return f |
|||
} |
|||
func term(ch chan float64, k float64) { |
|||
ch <- 4 * math.Pow(-1, k) / (2*k + 1) |
|||
} |
} |
||
Latest revision as of 13:28, 5 January 2014
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
Example:
package main
import "fmt"
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
func main() {
f := fib()
// Function calls are evaluated left-to-right.
fmt.Println(f(), f(), f(), f(), f())
}
// Concurrent computation of pi.
// See http://goo.gl/ZuTZM.
//
// This demonstrates Go's ability to handle
// large numbers of concurrent processes.
// It is an unreasonable way to calculate pi.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(pi(5000))
}
// pi launches n goroutines to compute an
// approximation of pi.
func pi(n int) float64 {
ch := make(chan float64)
for k := 0; k <= n; k++ {
go term(ch, float64(k))
}
f := 0.0
for k := 0; k <= n; k++ {
f += <-ch
}
return f
}
func term(ch chan float64, k float64) {
ch <- 4 * math.Pow(-1, k) / (2*k + 1)
}