this is probably not a new question but I can't find the answer anywhere.
With this code, on the line with the function call inside the loop, neither a :=
or a =
operator works.
I have a use case where I need a large array to be declared once, outside the for loop and updated in the function, then passed back. But that function also returns another variable which is different each time and used inside that loop.
Go playground link: 1
import "fmt"
func someFunc(names []string) (int, []string) {
foo := 35 // Just for the example
names = append(names, "Bob")
return foo, names
}
func main() {
names := []string{"Fred", "Mary"}
for i := 0; i < 10; i++ {
newVariable, names := someFunc(names) // This line is the problem
fmt.Println(newVariable)
}
}
How can I refactor this to get it working as intended?
What about just declaring newVariable before the := ?
for i := 0; i < 10; i++ {
var newVariable int
newVariable, names = someFunc(names)
fmt.Println(newVariable)
}