可以编写一个没有返回值或返回类型为Nil的函数。建议使用其他替代方案。

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

Is it possible to write a function without return or Nil return type. Suggest an alternative

问题

我这里有一个函数,它通过循环打印数字。我没有任何要返回的内容。我如何避免返回一个值呢?

func Problem1V3() {
	sum := 0
	for i := 3; i < 1000; i += 3 {
		fmt.Printf("i loop: %v", i)
	}
}

你可以将函数的返回类型设置为 voidnil,这样就不需要返回任何值了。在Go语言中,可以使用 voidnil 来表示没有返回值。在上面的代码中,我将函数的返回类型设置为 void,并且删除了 return 语句。这样,函数就不会返回任何值了。

英文:

I have a function here that loops through and print numbers. I do not have anything to return. How can I avoid this without having to return a value?

func Problem1V3() Nil {
sum := 0
    for i := 3; i &lt; 1000; i+=3 {
	    fmt.Printf(&quot;i loop: %v&quot;, i)
    }
    return Nil
}

答案1

得分: 14

我认为这应该可以工作。

func Problem1V3() {
    for i := 3; i < 1000; i+=3 {
        fmt.Printf("i循环: %v", i)
    }
}

你可以在http://play.golang.org/p/irUI1sCx_B上运行它。

英文:

I think this should work.

func Problem1V3() {
    for i := 3; i &lt; 1000; i+=3 {
        fmt.Printf(&quot;i loop: %v&quot;, i)
    }
}

You can run it at http://play.golang.org/p/irUI1sCx_B

huangapple
  • 本文由 发表于 2013年11月24日 23:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/20176162.html
匿名

发表评论

匿名网友

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

确定