Golang:未使用的函数

huangapple go评论97阅读模式
英文:

Golang: functions unused

问题

我最近开始学习golang,但是出现了一个奇怪的问题,即使我在代码中使用了一个函数,vscode也会提示该函数未使用。以下是代码:

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

语法是正确的,但程序仍然无法正常工作。

英文:

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

package prime  

import (
	&quot;fmt&quot;
)

func test(a int) (int) {

	to_ret := 1

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

func main() {
	sum := 2
	for i := 4; i &lt; 1000001; i++ {
		sum = sum + test(i)
	}
	fmt.Println(sum)
}

The syntax is correct, but still the program doesn't work.

答案1

得分: 1

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

> 通过将一个名为main的单个未导入的包与其导入的所有包进行链接,可以创建一个完整的程序。主包必须具有包名main,并声明一个不带参数且不返回值的main函数。
>
> go &gt; func main() { … } &gt;
>
> 程序的执行从初始化主包开始,然后调用main函数。当该函数调用返回时,程序退出。它不会等待其他(非主)goroutine完成。

将包名更改为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)
}
英文:

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.
>
>
&gt; func main() { … }
&gt;

>
> 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 (
	&quot;fmt&quot;
)

func test(a int) int {

	to_ret := 1

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

func main() {
	sum := 2
	for i := 4; i &lt; 1000001; i++ {
		sum = sum + test(i)
	}
	fmt.Println(sum)
}

huangapple
  • 本文由 发表于 2023年4月2日 15:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75910554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定