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

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

Leave a Reply