articles/golang.md: factorial example

This commit is contained in:
tocariimaa 2025-02-11 15:11:28 -03:00
parent 0f10be2d20
commit cce3bf40dd

View file

@ -35,3 +35,29 @@ Compiling and running:
```
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))
}
}
```