Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang: functions unused

I have recently started learning golang and for some strange reason even if I use a function in the code viscose says that the function is unused, here’s the code:

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

The syntax is right, but still the program doesn’t work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

https://go.dev/ref/spec#Program_execution

A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.

func main() { … }

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) 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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading