Just as a precursor I've just barely started learning Go recently. This is probably my 3rd day spending some time on it. I've been working with this error for a couple hours now, and I can't figure out what is wrong.
package main
import "fmt"
func main () {
nextFib := fibGenerator();
fmt.Println(nextFib());
fmt.Println(nextFib());
fmt.Println(nextFib());
fmt.Println(nextFib());
fmt.Println(nextFib());
}
func fibGenerator () uint {
var (
n uint = 0
back1 uint = 1
back2 uint = 0
)
_computeFib := func () uint {
if n == 0 {
n++
return 0
} else if n == 1 {
n++
return 1
}
fib := 1back + 2back // throws compile time error on this line
2back = 1back
1back = n
n++
return fib
}
return _computeFib
}
This is the error it throws: syntax error: unexpected name, expecting semicolon or newline or }
It's probably something simple, but with my limited knowledge in Go I can't put my finger on it. Any help would be appreciated.
EDIT: This is the final working function besides renaming my variables like the accepted answer says I also had to make the generator return a function that returns an int. I also had an error w/ Fibonacci logic.
func fibGenerator () func() uint {
var (
n uint = 0
back1 uint = 1
back2 uint = 0
)
_computeFib := func () uint {
if n == 0 {
n++
return 0
} else if n == 1 {
n++
return 1
}
fib := back1 + back2
back2 = back1
back1 = fib
n++
return fib
}
return _computeFib
}
You are trying to access variables called 1back
and 2back
but your variables are actually called back1
and back2
Refactoring issues aside, keep in mind that variables in go must begin with a letter, not a number. back1
and back2
are valid go variables, but 1back
and 2back
are not. See https://golang.org/ref/spec#Identifiers.