Go colon equals operator and a new variable

PHPz
Release: 2024-02-10 16:57:09
forward
490 people have browsed it

Go 冒号等于运算符和一个新变量

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.

Question content

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)
    }

}
Copy after login

How do I refactor this to work as expected?

Solution

How about declaring newVariable before :=?

for i := 0; i < 10; i++ {
    var newVariable int
    newVariable, names = someFunc(names)
    fmt.Println(newVariable)
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!