Golang: unused functions

WBOY
Release: 2024-02-06 11:42:10
forward
901 people have browsed it

Golang: unused functions

Question content

I recently started learning golang, and for some strange reasons, even if I use a function in the code, vscode says that the function Not used, the code is as follows:

package prime  

import (
    "fmt"
)

func test(a int) (int) {

    to_ret := 1

    for i := 2; i < a; i++ {
        if a % i == 0 {
            to_ret = 0
        }
    }
    return to_ret
}

func main() {
    sum := 2
    for i := 4; i < 1000001; i++ {
        sum = sum + test(i)
    }
    fmt.Println(sum)
}
Copy after login

The syntax is correct, but the program still won't run.


Correct answer


https://www.php.cn/link/4219840f5b401ebe7639efe00a1fb982

Create a complete program by transitively linking a single unimported package called the main package with all its imported packages. The main package must have the package name main and declare a function main that takes no parameters and returns no value.

func main() { … }
Copy after login

Program execution first initializes the main package, and then calls the main function. When this function call returns, the program exits. It does not wait for other (non-master) goroutines to complete.

Change the package name to main:

package main

import (
    "fmt"
)

func test(a int) int {

    to_ret := 1

    for i := 2; i < a; i++ {
        if a%i == 0 {
            to_ret = 0
        }
    }
    return to_ret
}

func main() {
    sum := 2
    for i := 4; i < 1000001; i++ {
        sum = sum + test(i)
    }
    fmt.Println(sum)
}
Copy after login

The above is the detailed content of Golang: unused functions. For more information, please follow other related articles on the PHP Chinese website!

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!