英文:
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 (
"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 correct, but still the program doesn't work.
答案1
得分: 1
https://go.dev/ref/spec#Program_execution
> 通过将一个名为main的单个未导入的包与其导入的所有包进行链接,可以创建一个完整的程序。主包必须具有包名main,并声明一个不带参数且不返回值的main函数。
>
> go > func main() { … } >
>
> 程序的执行从初始化主包开始,然后调用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.
>
>
> 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论