Home >Backend Development >Golang >Go colon equals operator and a new variable
php editor Xinyi is here to introduce a new feature to you - the Go colon equals operator and a new variable. The function of this operator is to create a new variable in the Go language and initialize it to the value of an expression. The introduction of this feature makes the code more concise and readable, while also reducing the amount of redundant code. By using the colon equals operator, we can assign a value to a variable while declaring it, improving the efficiency and readability of the code. In the following article, we will introduce the usage and precautions of this new feature in detail, hoping to bring help and inspiration to everyone.
This may not be a new question, but I can't find the answer anywhere.
With this code, neither the :=
nor the =
operators work on the function call line inside the loop.
I have a use case where I need to declare a large array once outside the for loop and update it in the function and then pass it back. But the function also returns another variable that is different every time and used within that loop.
Go to the 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 do I refactor this to work as expected?
How about declaring newVariable before :=?
for i := 0; i < 10; i++ { var newVariable int newVariable, names = someFunc(names) fmt.Println(newVariable) }
The above is the detailed content of Go colon equals operator and a new variable. For more information, please follow other related articles on the PHP Chinese website!