articles/golang.md: factorial example
This commit is contained in:
parent
0f10be2d20
commit
cce3bf40dd
1 changed files with 26 additions and 0 deletions
|
@ -35,3 +35,29 @@ Compiling and running:
|
||||||
```
|
```
|
||||||
go run hello.go
|
go run hello.go
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Factorial
|
||||||
|
```go
|
||||||
|
package main;
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// functions starting in uppercase are exported
|
||||||
|
func Fact(n uint) uint {
|
||||||
|
res := uint(1)
|
||||||
|
for n > 0 { // no while loop in Go
|
||||||
|
res *= n
|
||||||
|
n--
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Array literal, the `...` is used to infer its size
|
||||||
|
// If you instead left the [] empty it becomes an slice (heap allocated)
|
||||||
|
ns := [...]uint{0, 4, 10, 1, 5, 8}
|
||||||
|
for _, n := range ns {
|
||||||
|
fmt.Printf("Fact(%d) = %d\n", n, Fact(n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
Loading…
Add table
Reference in a new issue